Created
August 23, 2014 21:08
-
-
Save psyomn/9f7bd9d2a678f476de37 to your computer and use it in GitHub Desktop.
sendudp C file, modified from Paul Kryzanowski
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) { | |
| printf("usage:\n sendudp <host> <port> <message> [recv]\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); | |
| 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