向指定服务器的指定端口发送UDP包

//功能:读取文件文件,向指定服务器的指定端口发送UDP包,
//2015.9.26 OK

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>

//#define SERVER_PORT 8000
int SERVER_PORT = 8000;

int GetServerAddr(char * addrname,char *addrport)
{
char szTemp[512]={};
char IPaddr[512]={};
char port[512]={};
char *cfa;

FILE *file_fa = fopen("./send.conf","r+");
if(file_fa==NULL) //如果失败了
{
printf("open send.conf错误!\n");
exit(1); //中止程序
}

if((fgets(szTemp,255,file_fa)) != NULL ) //每次读一行
{
printf("szTemp=%s\n",szTemp);

cfa = strtok(szTemp, " ");
sprintf(port,"%s",cfa);
cfa = strtok(NULL, " ");
sprintf(IPaddr,"%s",cfa);
cfa = strtok(NULL, " ");
sprintf(port,"%s",cfa);

// printf("IPaddr=%s port=%s \n",IPaddr,port);

}
sprintf(addrname,"%s",IPaddr);
sprintf(addrport,"%s",port);
fclose(file_fa);
return 1;
}
int main(int argc,char **argv)
{
int cli_sockfd;
int len;
socklen_t addrlen;
char seraddr[14];
char serport[14];
struct sockaddr_in cli_addr;
char buffer[256];

GetServerAddr(seraddr,serport);
printf("GetServerAddr=%s,port=%s\n",seraddr,serport);

/* 建立socket*/
cli_sockfd=socket(AF_INET,SOCK_DGRAM,0);
if(cli_sockfd<0)
{
printf("I cannot socket success\n");
return 1;
}

/* 填写sockaddr_in*/
addrlen=sizeof(struct sockaddr_in);
bzero(&cli_addr,addrlen);
cli_addr.sin_family=AF_INET;
cli_addr.sin_addr.s_addr=inet_addr(seraddr);//将字符串转换为32位二进制网络字节序的IPV4地址
//cli_addr.sin_addr.s_addr=htonl(INADDR_ANY);
cli_addr.sin_port=htons( atoi(serport) );//主机字节顺序转化为网络字节顺序
// cli_addr.sin_port=htons(SERVER_PORT);

bzero(buffer,sizeof(buffer));
/* 从标准输入设备取得字符串*/
// len=read(STDIN_FILENO,buffer,sizeof(buffer));
sprintf(buffer,"%s","nihao");
len = sizeof(buffer)+1;
/* 将字符串传送给server端*/
while(1)
{
printf("sendword=%s\n",buffer);
sendto(cli_sockfd,buffer,len,0,(struct sockaddr*)&cli_addr,addrlen);
sleep(2);
}
/* 接收server端返回的字符串*/
len=recvfrom(cli_sockfd,buffer,sizeof(buffer),0,(struct sockaddr*)&cli_addr,&addrlen);
//printf("receive from %s\n",inet_ntoa(cli_addr.sin_addr));
printf("receive: %s",buffer);
close(cli_sockfd);
}

posted @ 2015-09-26 18:19  周人假的  阅读(2791)  评论(0编辑  收藏  举报