xref: /haiku/src/tests/system/network/icmp/udp_unreachable.cpp (revision 5e54f6d4f9dd607ae2afcea4fe72f2f1763e4b5e)
1 /*
2  * Copyright 2008-2010, Haiku, Inc. All Rights Reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Yin Qiu
7  */
8 
9 
10 #include <errno.h>
11 #include <netdb.h>
12 #include <netinet/in.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <sys/socket.h>
17 #include <unistd.h>
18 
19 
20 #define MAX_LENGTH 4096
21 
22 
23 extern const char* __progname;
24 
25 
26 int
main(int argc,char ** argv)27 main(int argc, char** argv)
28 {
29 	if (argc < 2) {
30 		fprintf(stderr, "Usage: %s <host> [<port>]\n"
31 			"Sends a UDP datagram to the specified target.\n"
32 			"<port> defaults to 9999.\n", __progname);
33 		return 1;
34 	}
35 
36 	struct hostent* host = gethostbyname(argv[1]);
37 	if (host == NULL) {
38 		perror("gethostbyname");
39 		return 1;
40 	}
41 
42 	uint16_t port = 9999;
43 	if (argc > 2)
44 		port = atol(argv[2]);
45 
46 	struct sockaddr_in serverAddr;
47 	memset(&serverAddr, 0, sizeof(struct sockaddr_in));
48 	serverAddr.sin_family = AF_INET;
49 	serverAddr.sin_port = htons(port);
50 	serverAddr.sin_addr = *((struct in_addr*)host->h_addr);
51 
52 	int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
53 	// We need to call connect() to receive async ICMP errors
54 	if (connect(sockfd, (struct sockaddr*)&serverAddr,
55 			sizeof(struct sockaddr_in)) < 0) {
56 		fprintf(stderr, "Calling connect() on UDP socket failed: %s\n",
57 			strerror(errno));
58 		return 1;
59 	}
60 
61 	const char* string = "Hello";
62 	ssize_t bytes = write(sockfd, string, strlen(string));
63 	if (bytes < 0) {
64 		fprintf(stderr, "UDP send failed: %s\n", strerror(errno));
65 		return 1;
66 	}
67 
68 	printf("%zd bytes sent to remote server.\n", bytes);
69 
70 	char buffer[MAX_LENGTH];
71 	bytes = read(sockfd, buffer, MAX_LENGTH);
72 	if (bytes > 0) {
73 		printf("Received %zd bytes from remote host\n", bytes);
74 		printf("%s\n", buffer);
75 	} else {
76 		// We are expecting this
77 		printf("Error: %s\n", strerror(errno));
78 	}
79 	close(sockfd);
80 	printf("Socket closed.\n");
81 
82 	return 0;
83 }
84