/*
UDP Broadcast Echo Client
Author :Andrew Huang
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
int main(int argc ,char * argv[])
{
unsigned short port = 9002;
int sock;
char ipaddr[32] = "10.1.0.255";
char buf[32] = "hello server";
struct sockaddr_in serv_addr;
int len;
socklen_t addr_len;
if(argc >1)
{
port = (unsigned short)atoi(argv[1]);
}
if(argc >2)
{
memset(ipaddr,0,sizeof(ipaddr));
strncpy(ipaddr,argv[2],sizeof(ipaddr)-1);
}
if(argc > 3)
{
memset(buf,0,sizeof(buf));
strncpy(buf,argv[3],sizeof(buf)-1);
}
printf("connect server %s:%d,buf %s\n",ipaddr,port,buf);
//第一步:创建一个IPV4,UDP,可以运行所有协议的SOCKET
sock = socket(PF_INET,SOCK_DGRAM,0);
if(sock == -1)
{
perror("socket");
return -1;
}
//打开广播选项
{
int val = 1;
if(setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *) &val, sizeof (val)) == -1)
{
perror("setsockopt");
}
}
fprintf(stdout,"send broadcast on %s:%d\n",ipaddr,port);
//第二步:对于客户端,port可用任意一个编号,如果不使用bind,协议栈会自动分配没用的端口0
// 省略bind ....
memset(&serv_addr,0,sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
serv_addr.sin_addr.s_addr = inet_addr(ipaddr);
sendto(sock,buf,strlen(buf)+1,0,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
{//可以从socket取到自己所绑定的端口和地址
memset(&serv_addr ,0 ,sizeof(serv_addr));
addr_len = sizeof(serv_addr);
getsockname(sock,(struct sockaddr *)&serv_addr,&addr_len);
fprintf(stdout,"local addr %s ,port %d\n",inet_ntoa(serv_addr.sin_addr),ntohs(serv_addr.sin_port));
}
len = recvfrom(sock,buf,sizeof(buf),0,NULL,NULL);
if(len >0)
{
buf[len] = 0;
fprintf(stdout,"SERVER:%s\n",buf);
}
//关闭socket
close(sock);
}
|