服务端:
/*
Refernce:
http://www.linuxidc.com/Linux/2011-06/37951.htm
http://www.oschina.net/code/snippet_153782_16563
*/
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int main()
{
struct sockaddr_in s_in;//server address structure
struct sockaddr_in c_in;//client address structure
int l_fd,c_fd;
socklen_t len;
char buf[1024];//content buff area
char addr_p[16];
int port = 8009;
memset((void *)&s_in,0,sizeof(s_in));
//bzero((void *)&s_in,sizeof(s_in));
s_in.sin_family = AF_INET;//IPV4 communication domain
s_in.sin_addr.s_addr = INADDR_ANY;//accept any address
s_in.sin_port = htons(port);//change port to netchar
l_fd = socket(AF_INET,SOCK_STREAM,0);//socket(int domain, int type, int
protocol)
/*bind(int sockfd,struct sockaddr *my_addr, int addrlen);
sockfd是调用socket函数返回的socket描述符,my_addr是一个指向包含有本机IP地址及端口号等信息的sockaddr类型的指针;addrlen常被设置为sizeof(struct sockaddr)
*/
bind(l_fd,(struct sockaddr *)&s_in,sizeof(s_in));
listen(l_fd,10);//lisiening start
cout<
while(1){
/*
accept()函数让服务器接收客户的连接请求.
accept(int sockfd, void *addr, int *addrlen);
sockfd是被监听的socket描述符,addr通常是一个指向sockaddr_in变量的指针,该变量用来存放提出连接请求服务的主机的信息(某台主机从某个端口发出该请求);addrten通常为一个指向值为sizeof(struct sockaddr_in)的整型指针变量。出现错误时accept函数返回-1并置相应的errno值。
当accept函数监视的socket收到连接请求时,socket执行体将建立一个新的socket,执行体将这个新socket和请求连接进程的地址联系起来
*/
c_fd = accept(l_fd,(struct sockaddr *)&c_in,&len);
int n = read(c_fd,buf,1024);//read the message send by client
inet_ntop(AF_INET,&c_in.sin_addr,addr_p,16);//“二进制整数” -> “点分十进制
*inet_ntop(int af, const void *src, char *dst, socklen_t cnt);
cout<
write(c_fd,buf,n);//sent message back to client
close(c_fd);
}
cout<
return 0;
}
客户端:
#include
#include
#include
#include
#include
#include
#include
using namespace std;
int main(){
struct sockaddr_in s_in;
char buf[100];
int s_fd;
int port = 8000;
char *str = "socket net program";
char *sip = "127.0.0.1";
memset((void *)&s_in,0,sizeof(s_in));
s_in.sin_family = AF_INET;
s_in.sin_port = htons(port);
inet_pton(AF_INET,sip,(void *)&s_in.sin_addr);
s_fd = socket(AF_INET,SOCK_STREAM,0);
/*
面向连接的客户程序使用connect函数来配置socket并与远端服务器建立一个TCP连接int connect(int sockfd, struct sockaddr *serv_addr,int addrlen)sockfd是socket函数返回的socket描述符;serv_addr是包含远端主机IP地址和端口号的指针;addrlen是远端地址结构的长度
*/
connect(s_fd,(struct sockaddr *)&s_in,sizeof(s_in));
cout<
write(s_fd,str,strlen(str)+1);
read(s_fd,buf,100);
cout<
close(s_fd);
}