#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; void dg_cli(FILE *fp, int sockfd, struct sockaddr * pservaddr, socklen_t servlen) { int n; char sendline[maxline], recvline[maxline+1]; char errbuff[maxline]; struct sockaddr_in localaddr; socklen_t len=sizeof(localaddr); while(fgets(sendline, maxline, fp) != NULL) { memset(recvline, 0, sizeof(recvline)); if(sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen)<0) { strerror_r(errno, errbuff, maxline); fprintf(stderr, "sendto error: %s\n", errbuff); exit(-1); } if((n=recvfrom(sockfd, recvline, maxline, 0, pservaddr, &servlen)) < 0) { strerror_r(errno, errbuff, maxline); fprintf(stderr, "read error: %s\n", errbuff); exit(-1); } if(getsockname(sockfd, (struct sockaddr *)&localaddr, &len)<0) { strerror_r(errno, errbuff, maxline); fprintf(stderr, "getsockname error: %s\n", errbuff); exit(-1); } recvline[n]=0; printf("%s", recvline); printf("local ip: %s, local port: %d\n", inet_ntop(AF_INET, &localaddr.sin_addr, errbuff, sizeof(errbuff)), ntohs(localaddr.sin_port)); } } 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(13); inet_pton(AF_INET, argv[1], &servaddr.sin_addr); dg_cli(stdin, sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); return 0; }
标签:udp,include,int,recvline,获取,sendline,sockfd,maxline,客户端 From: https://www.cnblogs.com/donggongdechen/p/17294539.html