Server program: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #
Include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #define PORT 8082 #define BUFSIZE 512
Char buf[bufsize+1];
int main () {//step 1th creates socket int sockfd=socket (af_inet,sock_dgram,0);
The 2nd step is to set the address structure body struct sockaddr_in svraddr;
svraddr.sin_family=af_inet;//uses Internet Protocol svraddr.sin_port=htons (port);
Inet_aton ("0.0.0.0", &svraddr.sin_addr);
Step 3rd Binding int Ret=bind (SOCKFD, (struct sockaddr*) &svraddr,sizeof (SVRADDR));
if (ret<0) {printf ("Cannot bind!\r\n"); exit (-1);
while (1) {struct sockaddr_in cli;
int len=sizeof (CLI);
int Z=recvfrom (sockfd,buf,bufsize,0, (struct sockaddr*) &cli,&len);//6th step read Socket buf[z]= ' ""; printf ("%s\r\n", buf);//print}//client program CLI.C//from http://www.bianceng.cn #include <stdio.h> #include ; stdlib.h> #include <string.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h>
#include <unistd.h> #define PORT 8082 #define BufSize Char buf[bufsize+1];
int main () {//step 1th creates an individual socket int sockfd=socket (af_inet,sock_dgram,0);
The 2nd step is to set up the addr structure body struct sockaddr_in svraddr;
svraddr.sin_family=af_inet;//uses Internet Protocol svraddr.sin_port=htons (port);
Inet_aton ("127.0.0.1", &svraddr.sin_addr);
The 3rd step connects the server//connect (SOCKFD, (struct sockaddr*) &svraddr,sizeof (SVRADDR));
while (1) {scanf ("%s", buf); SendTo (Sockfd,buf,strlen (BUF), 0, (struct sockaddr*) &svraddr,sizeof (SVRADDR)); Step 4th writes the string to a socket}}
This article from the "Live Well" blog, please be sure to keep this source http://wolfword.blog.51cto.com/4892126/1224934
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Servers/zs/