Created
October 21, 2014 20:09
-
-
Save psyomn/e6fd08f537578ccc35ee to your computer and use it in GitHub Desktop.
A nice-y debugging tool if you want to send plain udp packets, and wait for listens
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <sys/types.h> | |
| #include <sys/socket.h> | |
| #include <netinet/in.h> | |
| #include <stdio.h> | |
| #include <string.h> | |
| #include <netdb.h> | |
| /* somewhat modified version of Paul Kryzanowski's example | |
| * https://www.cs.rutgers.edu/~pxk/417/notes/sockets/udp.html | |
| */ | |
| int | |
| main(int argc, char* argv[]) { | |
| if (argc != 4 && argc != 5 && argc != 6) { | |
| printf("usage:\n sendudp <host> <port> <message> [recv] [times]\n"); | |
| return -1; | |
| } | |
| int sock; | |
| struct hostent* hp; | |
| struct sockaddr_in servaddr; | |
| char * my_message = argv[3]; | |
| servaddr.sin_family = AF_INET; | |
| servaddr.sin_port = htons(atoi(argv[2])); | |
| hp = gethostbyname(argv[1]); | |
| if (!hp) { | |
| printf("problems\n"); | |
| return 0; | |
| } | |
| sock = socket (AF_INET, SOCK_DGRAM, 0); | |
| if (sock < 0) { | |
| printf("problem opening socket"); | |
| } | |
| memcpy((void*)&servaddr.sin_addr, | |
| hp->h_addr_list[0], | |
| hp->h_length); | |
| int sendto_ret; | |
| sendto_ret = sendto(sock, my_message, strlen(my_message), 0, | |
| (struct sockaddr*)&servaddr, sizeof(servaddr)); | |
| if (argc >= 5 && !strcmp(argv[4],"recv")) { | |
| int buffsize = 18000; | |
| char buffer[buffsize]; /* Will not surpass this */ | |
| int ret; | |
| struct sockaddr_in remote; | |
| socklen_t addlen = sizeof(remote); | |
| memset(buffer, 0, buffsize); | |
| if (argc == 6) { | |
| int times = atoi(argv[5]); | |
| int index; | |
| printf("Waiting for %d response(s)\n", index); | |
| for (index = 0; index < times; ++index) { | |
| ret = recvfrom(sock, buffer, buffsize, 0, | |
| (struct sockaddr*)&remote, &addlen); | |
| printf("[%s]\n", buffer); | |
| } | |
| } | |
| else { | |
| printf("Waiting for response...\n"); | |
| ret = recvfrom(sock, buffer, buffsize, 0, | |
| (struct sockaddr*)&remote, &addlen); | |
| printf("[%s]\n", buffer); | |
| } | |
| } | |
| if (sendto_ret < 0) { | |
| perror("problem sending "); | |
| } | |
| close(sock); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment