分类: LINUX
2013-05-07 10:13:29
要使用UDP协议进行通讯,需要以下几个步骤:
服务器端代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc,char **argv) {
int z;
char *srvr_addr = NULL;
struct sockaddr_in adr_inet;
struct sockaddr_in adr_clnt;
int len_inet;
int s;
char dgram[512];
char dtfmt[512];
srvr_addr = "127.0.0.23";
s = socket(AF_INET,SOCK_DGRAM,0);
memset(&adr_inet,0,sizeof adr_inet);
adr_inet.sin_family = AF_INET;
adr_inet.sin_port = htons(9090);
adr_inet.sin_addr.s_addr =inet_addr(srvr_addr);
len_inet = sizeof adr_inet;
z = bind(s,(struct sockaddr *)&adr_inet,len_inet);
for (;;) {
len_inet = sizeof adr_clnt;
z = recvfrom(s, dgram, sizeof dgram, 0,(struct sockaddr *)&adr_clnt, &len_inet);
dgram[z] = 0;
printf("%s:%s\n",inet_ntoa(adr_clnt.sin_addr),dgram);
fputs("Enter:",stdout);
if ( !fgets(dtfmt,sizeof dtfmt,stdin) )
break;
z = sendto(s,dtfmt,strlen(dtfmt),0,(struct sockaddr *)&adr_clnt,len_inet);
}
close(s);
return 0;
}
客户端代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc,char **argv) {
int z;
int x;
char *srvr_addr = NULL;
struct sockaddr_in adr_srvr;
struct sockaddr_in adr;
int len_inet;
int s;
char dgram[512];
srvr_addr = "127.0.0.23"
memset(&adr_srvr,0,sizeof adr_srvr);
adr_srvr.sin_family = AF_INET;
adr_srvr.sin_port = htons(9090);
adr_srvr.sin_addr.s_addr =
inet_addr(srvr_addr);
len_inet = sizeof adr_srvr;
s = socket(AF_INET,SOCK_DGRAM,0);
for (;;) {
fputs("Enter:",stdout);
if ( !fgets(dgram,sizeof dgram,stdin) )
break;
z = strlen(dgram);
if ( z > 0 && dgram[--z] == '\n' )
dgram[z] = 0;
z = sendto(s,dgram,strlen(dgram),0,(struct sockaddr *)&adr_srvr,len_inet);
x = sizeof adr;
z = recvfrom(s,dgram,sizeof dgram, 0,(struct sockaddr *)&adr, &x);
dgram[z] = 0;
printf("%s:%s\n",inet_ntoa(adr.sin_addr),dgram);
}
close(s);
return 0;
}