1、代码实现客户端接入,打印connect
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
//#include <linux/in.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
int main()
{
int s_fd;
//1.socket
s_fd=socket(AF_INET,SOCK_STREAM,0);
if(s_fd==-1){
perror("socket");
exit(-1);
}
//2.bind
struct sockaddr_in s_addr;
s_addr.sin_family=AF_INET;
s_addr.sin_port=htons(8989);
inet_aton("192.168.1.9",&s_addr.sin_addr);
bind(s_fd,(struct sockaddr *)&s_addr,sizeof(struct sockaddr_in));
//3.listen
listen(s_fd,10);
//4.accept
int c_fd=accept(s_fd,NULL,NULL);
//5.read
//6.write
printf("connect\n");
while(1);
return 0;
}
编译运行此代码;
打开windos中cmd指令先ping该ip号看能不能ping通;如果能ping通,输入telnet ip号 端口号。则该服务器连接客户端成功代码向下运行,打印出connect字符。
*注:windos10系统默认不开启telnet,需要查询开启方法进行开启,再使用该命令。
修改代码:添加获取客户端地址、数据的交互收发
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
//#include <linux/in.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int s_fd;
char readbuf[128];
int nread;
char *msg="i get your message\n";
struct sockaddr_in s_addr;
struct sockaddr_in c_addr;
memset(&s_addr,0,sizeof(struct sockaddr_in));
memset(&c_addr,0,sizeof(struct sockaddr_in));
//1.socket
s_fd=socket(AF_INET,SOCK_STREAM,0);
if(s_fd==-1){
perror("socket");
exit(-1);
}
//2.bind
s_addr.sin_family=AF_INET;
s_addr.sin_port=htons(8989);
inet_aton("192.168.1.9",&s_addr.sin_addr);
bind(s_fd,(struct sockaddr *)&s_addr,sizeof(struct sockaddr_in));
//3.listen
listen(s_fd,10);
//4.accept
int clen=sizeof(struct sockaddr_in);
int c_fd=accept(s_fd,(struct sockaddr*)&c_addr,&clen);
if(c_fd==-1){
perror("accept");
}
printf("connect\n");
printf("get connect:%s\n",inet_ntoa(c_addr.sin_addr));
//5.read
nread=read(c_fd,readbuf,128);
if(nread==-1){
perror("read");
}else{
printf("get message:%d,%s\n",nread,readbuf);
}
//6.write
write(c_fd,msg,strlen(msg));
return 0;
}
代码编译运行:
重新alt+ctrl+t开个界面,
telnet+ip地址+端口号实现连接
输出结果:
//输入: telnet 192.168.1.9 8989
Trying 192.168.1.9...
Connected to 192.168.1.9.
Escape character is '^]'.
yangzerui
i get your message
Connection closed by foreign host.