udp回射客户端
#include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <string.h> const int maxline=4096; char *sock_ntop(const struct sockaddr *sa, socklen_t salen) { char portstr[8]; static char str[128]; switch(sa->sa_family) { case AF_INET: { struct sockaddr_in * sin = (struct sockaddr_in *)sa; if(inet_ntop(AF_INET, &sin->sin_addr, str, sizeof(str)) == NULL) { return NULL; } if(ntohs(sin->sin_port) != 0) { snprintf(portstr, sizeof(portstr), ":%d", ntohs(sin->sin_port)); strcat(str, portstr); } return str; } } } void dg_cli(FILE *fp, int sockfd, const struct sockaddr * pservaddr, socklen_t servlen) { int n; char sendline[maxline], recvline[maxline+1]; char errbuff[maxline]; socklen_t len; struct sockaddr *preply_addr; if((preply_addr=malloc(servlen)) == NULL) { strerror_r(errno, errbuff, maxline); fprintf(stderr, "malloc error: %s\n", errbuff); exit(-1); } while(fgets(sendline, maxline, fp) != NULL) { if(sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen)<0) { strerror_r(errno, errbuff, maxline); fprintf(stderr, "sendto error: %s\n", errbuff); exit(-1); } len=servlen; if((n=recvfrom(sockfd, recvline, maxline, 0, preply_addr, &len))<0) { strerror_r(errno, errbuff, maxline); fprintf(stderr, "recvfrom error: %s\n", errbuff); exit(-1); } printf("reply from %s\n", sock_ntop(preply_addr, len)); if(len != servlen || memcmp(pservaddr, preply_addr, len) != 0) { printf("reply from %s (ignored)\n", sock_ntop(preply_addr, len)); continue; } recvline[n]=0; fputs(recvline, stdout); } } int main(int argc, char **argv) { int sockfd; struct sockaddr_in servaddr; char errbuff[maxline]; if(argc != 2) { fprintf(stderr, "usage: udpcli <IPaddress>\n"); exit(-1); } if((sockfd=socket(AF_INET, SOCK_DGRAM, 0))<0) { strerror_r(errno, errbuff, maxline); fprintf(stderr, "socket error: %s\n", errbuff); exit(-1); } memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(9999); inet_pton(AF_INET, argv[1], &servaddr.sin_addr); dg_cli(stdin, sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); return 0; }