zhr811022 发表于 2011-12-20 09:47

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