Created
November 7, 2018 03:15
-
-
Save shangzongyu/aef6e4775a13842e33da1e663f40dfde to your computer and use it in GitHub Desktop.
udp client in C
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 <stdio.h> | |
#include <string.h> | |
#include <sys/types.h> | |
#include <netinet/in.h> | |
#include <sys/socket.h> | |
#include <errno.h> | |
#include <stdlib.h> | |
#include <arpa/inet.h> | |
int main(int argc,char **argv) | |
{ | |
struct sockaddr_in s_addr; | |
int sock; | |
int addr_len; | |
int len; | |
char buff[128]; | |
int yes; | |
/*创建socket*/ | |
if((sock=socket(AF_INET,SOCK_DGRAM,0))==-1) | |
{ | |
perror("socket"); | |
exit(errno); | |
} | |
else | |
{ | |
printf("socket created success!!!\n"); | |
} | |
yes=1; | |
setsockopt(sock,SOL_SOCKET,SO_BROADCAST,&yes,sizeof(yes)); | |
/**/ | |
s_addr.sin_family=AF_INET; | |
if(argv[2]) | |
s_addr.sin_port=htons(atoi(argv[2])); | |
else | |
s_addr.sin_port=htons(554); | |
if(argv[1]) | |
s_addr.sin_addr.s_addr=inet_addr(argv[1]); | |
else | |
{ | |
printf("消息必须有一个接收者!\n"); | |
exit(0); | |
} | |
/*发送UDP消息*/ | |
addr_len=sizeof(s_addr); | |
strcpy(buff,"hello udp server,this is udp client!"); | |
len=sendto(sock,buff,strlen(buff),0,(struct sockaddr*) &s_addr,addr_len); | |
if(len<0) | |
{ | |
printf("\nsendto error.\n"); | |
return 3; | |
} | |
printf("sendto succss.\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment