当前位置: 技术问答>linux和unix
linux下的socket 编程
来源: 互联网 发布时间:2017-04-28
本文导语: #include #include #include #include #include #include #include #include #define SERVPORT 3333 #define BACKLOG 10 main() { int sin_size; // 這個變數未定義 int sockfd,client_fd; struct sockaddr_in my_addr; struct sockaddr_in r...
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVPORT 3333
#define BACKLOG 10
main()
{
int sin_size; // 這個變數未定義
int sockfd,client_fd;
struct sockaddr_in my_addr;
struct sockaddr_in remote_addr;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror( "socket创建出错!"); exit(1);
}
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero( &(my_addr.sin_zero),8);
if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)) == -1) {
perror( "bind出错!");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1) {
perror( "listen出错!");
exit(1);
}
while(1) {
sin_size = sizeof(struct sockaddr_in);
if ((client_fd = accept(sockfd, (struct sockaddr *) &remote_addr, &sin_size))==-1) {
perror( "accept出错");
continue;
}
printf( "received a connection from %sn", inet_ntoa(remote_addr.sin_addr));
if (!fork()) {
if (send(client_fd, "Hello, you are connected!n", 26, 0) == -1)
perror( "send出错!");
close(client_fd);
exit(0);
}
close(client_fd);
}
}
// client.c
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVPORT 3333
#define MAXDATASIZE 100
int main(int argc, char *argv[])
{
int sockfd, recvbytes;
char buf[MAXDATASIZE];
struct hostent *host;
struct sockaddr_in serv_addr;
if (argc h_addr);
bzero( &(serv_addr.sin_zero),8);
if (connect(sockfd, (struct sockaddr *) &serv_addr,
sizeof(struct sockaddr)) == -1) {
perror("connect出错!");
exit(1);
}
if ((recvbytes=recv(sockfd, buf, MAXDATASIZE, 0)) ==-1) {
perror("recv出错!");
exit(1);
}
buf[recvbytes] = '';
printf( "Received: %s",buf);
close(sockfd);
return 0;
}
以上代码是来自于http://bbs.csdn.net/topics/300149431回帖中@fetag这位大侠的代码,他的运行结果是:
[root][~]# ./server &
[1] 3282
[root][~]# gcc -o client client.c
[root][~]# ./client 192.168.198.128
received a connection from 192.168.198.128
Received: Hello, you are connected!
我的linux是在虚拟机下的,但是我照着做却没办法像连接中所说的正常运行,我的运行结果如下(我尝试了两种方法,可是都是失败的):
[root@localhost Myproject]# ./ftpS &
[1] 8954
[root@localhost Myproject]# gcc -o ftpC ftpC.c
[root@localhost Myproject]# ./client 127.0.0.1
connect to server error!
[root@localhost Myproject]# ./ftpS &为什么,难不成和ip的配置有关吗,我window是连着无线的,linux下是桥连接的方式,ifconfig eth0 出来的ip是192.168.1.109。求大神指点指点。谢谢!
[1] 8954
[root@localhost Myproject]# gcc -o ftpC ftpC.c
[root@localhost Myproject]# ./client 192.168.1.109
connect to server error!
|