udp client and server linux下
<P><FONT style="BACKGROUND-COLOR: #a0d3a0">udp server</FONT></P><P><FONT style="BACKGROUND-COLOR: #a0d3a0">///////////////////////////////////////////////////////</FONT></P>
<P><FONT style="BACKGROUND-COLOR: #a0d3a0">#include <arpa/inet.h><BR>#include <netinet/in.h><BR>#include <stdio.h><BR>#include <sys/types.h><BR>#include <sys/socket.h><BR>#include <unistd.h></FONT></P>
<P><FONT style="BACKGROUND-COLOR: #a0d3a0">#define BUFLEN 512<BR>#define NPACK 10<BR>#define PORT 9876</FONT></P>
<P><FONT style="BACKGROUND-COLOR: #a0d3a0">//#define SRV_IP "116.236.218.246"<BR>#define SRV_IP "172.26.59.244"</FONT></P>
<P><FONT style="BACKGROUND-COLOR: #a0d3a0">void diep(char *s)<BR>{<BR> perror(s);<BR> exit(1);<BR>}</FONT></P>
<P><FONT style="BACKGROUND-COLOR: #a0d3a0">int main(void)<BR>{<BR> struct sockaddr_in si_me, si_other;<BR> int s, i, slen=sizeof(si_other);<BR> char buf;</FONT></P>
<P><FONT style="BACKGROUND-COLOR: #a0d3a0"> if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)<BR> diep("socket");</FONT></P>
<P><FONT style="BACKGROUND-COLOR: #a0d3a0"> memset((char *) &si_me, 0, sizeof(si_me));<BR> si_me.sin_family = AF_INET;<BR> si_me.sin_port = htons(PORT);<BR> si_me.sin_addr.s_addr = htonl(INADDR_ANY);//inet_addr(SRV_IP);<BR> if (bind(s, &si_me, sizeof(si_me))==-1)<BR> diep("bind");</FONT></P>
<P><FONT style="BACKGROUND-COLOR: #a0d3a0"> for (i=0; i<NPACK; i++) {<BR> if (recvfrom(s, buf, BUFLEN, 0, &si_other, &slen)==-1)<BR> diep("recvfrom()");<BR> printf("Received packet from %s:%d\nData: %s\n\n",<BR> inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf);<BR> sleep(9);<BR> sprintf(buf, "MSG FROM Server");<BR> printf("To reply data to %s:%d\nData: %s\n\n",<BR> inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf);<BR> if (sendto(s, buf, strlen(buf), 0, &si_other, slen)==-1)<BR> diep("sendto()");<BR> }</FONT></P>
<P><FONT style="BACKGROUND-COLOR: #a0d3a0"> close(s);<BR> return 0;<BR>}</FONT></P>
<P><FONT style="BACKGROUND-COLOR: #a0d3a0">///////////////////////////////////////////////////////////////////////////////</FONT></P>
<P><FONT style="BACKGROUND-COLOR: #a0d3a0">udp client</FONT></P>
页:
[1]