y9528
8/27/2017 - 2:21 PM

UDP_Client

UDP_Client

#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;
}