-
yyp@ubuntu:~$ netstat -anp|grep a.out
-
(并非所有进程都能被检测到,所有非本用户的进程信息将不会显示,如果想看到所有信息,则必须切换到 root 用户)
-
tcp 0 0 0.0.0.0:1234 0.0.0.0:* LISTEN 1230/a.out
-
tcp 0 0 10.2.1.128:44825 10.2.1.128:1234 ESTABLISHED 1231/a.out
-
tcp 0 0 10.2.1.128:1234 10.2.1.128:44825 ESTABLISHED 1230/a.out
accept会创建一个新的socket,所以服务器+客户端的一次连接会有三个端口,结果如上所示。
下面是client和server的源代码
-
#include <iostream>
-
#include <sys/types.h> /* See NOTES */
-
#include <sys/socket.h>
-
#include <netinet/in.h>
-
#include <unistd.h>
-
#include <stdint.h>
-
#include <stdlib.h>
-
#include <string.h>
-
using namespace std;
-
-
int main()
-
{
-
int fd;
-
fd = socket(AF_INET, SOCK_STREAM, 0);
-
if(fd ==-1)
-
{
-
cout<<"socket error"<<endl;
-
exit(-1);
-
}
-
cout<<"socket ok"<<endl;
-
-
struct sockaddr_in my_addr;
-
socklen_t peer_addr_size;
-
-
memset(&my_addr, 0, sizeof(struct sockaddr_in));
-
-
my_addr.sin_family=AF_INET;
-
my_addr.sin_port=htons(1234);
-
my_addr.sin_addr.s_addr=htonl(INADDR_ANY);
-
-
int bindFd = bind(fd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr_in));
-
if(bindFd==-1){
-
cout<<"bind Error"<<endl;
-
close(fd);
-
exit(-1);
-
}
-
cout<<"bind ok"<<endl;
-
char buffer[512];
-
int liFd = listen(fd, 5);
-
if(liFd==-1)
-
{
-
cout<<"lsten error"<<endl;
-
exit(-1);
-
}
-
-
cout<<"listening"<<endl;
-
-
while(true)
-
{
-
cout<<"ready to accept"<<endl;
-
struct sockaddr_in peer;
-
int acceptFd;
-
socklen_t len=sizeof(peer);
-
acceptFd = accept(fd,(struct sockaddr *)&peer, &len);
-
if(acceptFd == -1)
-
{
-
cout<<"accept error"<<endl;
-
exit(-1);
-
}
-
cout<<"accepted"<<endl;
-
while(true){}
-
write(acceptFd, "hello", sizeof("hello"));
-
cout<<"write hello"<<endl;
-
close(acceptFd);
-
}
-
-
-
close(fd);
-
-
return 0;
-
}
client:
-
#include <iostream>
-
#include <stdio.h>
-
#include <sys/types.h> /* See NOTES */
-
#include <sys/socket.h>
-
#include <iostream>
-
#include <stdlib.h>
-
#include <netinet/in.h>
-
#include <arpa/inet.h>
-
#include <strings.h>
-
using namespace std;
-
-
int main()
-
{
-
int sfd = socket(AF_INET, SOCK_STREAM, 0);
-
if(sfd==-1)
-
{
-
cout<<"socket error"<<endl;
-
exit(-1);
-
}
-
-
cout<<"socket ok"<<endl;
-
-
struct sockaddr_in server;
-
bzero(&server, sizeof(server));
-
server.sin_family = AF_INET;
-
server.sin_port = htons(1234);
-
// server.sin_addr.s_addr = inet_addr("10.2.1.128");
-
inet_pton(AF_INET, "10.2.1.128", &server.sin_addr);
-
cout<<"ready to connect"<<endl;
-
printf("%u\n", server.sin_addr.s_addr>>24);
-
int cfd = connect(sfd, (struct sockaddr*)&server, sizeof(server));
-
if(cfd==-1)
-
{
-
cout<<"connect error"<<endl;
-
exit(-1);
-
}
-
-
cout<<"connected"<<endl;
-
char buf[1000];
-
while(true){}
-
read(cfd,buf, 1000);
-
cout<<buf<<endl;
-
close(cfd);
-
close(sfd);
-
return 0;
-
}
阅读(2954) | 评论(0) | 转发(0) |