学习Linux下的网络编程时,写的例子,bind() 这块报错,求大神指导一下,原因。下面是代码和错误 10
[root@bogonDesktop]#./tcp_serBind()error:Invalidargument[root@bogonDesktop]#cattcp_se...
[root@bogon Desktop]# ./tcp_ser
Bind() error: Invalid argument
[root@bogon Desktop]# cat tcp_ser.c
#include <stdio.h>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 9999
#define BACKLOG 1
main()
{
int listenfd, connectfd;
struct sockaddr_in server;
struct sockaddr_in client;
socklen_t addrlen;
listenfd = socket(AF_INET6, SOCK_STREAM, 0);
if(listenfd ==-1)
{
perror("socket() error.");
exit(1);
}
int opt = SO_REUSEADDR ;
setsockopt(listenfd, SOL_SOCKET,SO_REUSEADDR,&opt ,sizeof(opt));
bzero(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(PORT);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(listenfd,(struct sockaddr *) &server,sizeof(server)) == -1)
{
perror("Bind() error");
exit(1);
}
if(listen(listenfd,BACKLOG) == -1)
{
perror("listen() error.\n");
exit(1);
}
int len = sizeof(client);
if((connectfd = accept(listenfd,(struct sockaddr *)&client,&addrlen)) == -1)
{
perror("accept() error\n");
exit(1);
}
printf("You got a connection from client's ip is %s,port is%d\n",inet_ntoa(client.sin_addr),htons(client.sin_port));
send(connectfd,"Welcome\n",8,0);
close(connectfd);
close(listenfd);
}
[root@bogon Desktop]# 展开
Bind() error: Invalid argument
[root@bogon Desktop]# cat tcp_ser.c
#include <stdio.h>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 9999
#define BACKLOG 1
main()
{
int listenfd, connectfd;
struct sockaddr_in server;
struct sockaddr_in client;
socklen_t addrlen;
listenfd = socket(AF_INET6, SOCK_STREAM, 0);
if(listenfd ==-1)
{
perror("socket() error.");
exit(1);
}
int opt = SO_REUSEADDR ;
setsockopt(listenfd, SOL_SOCKET,SO_REUSEADDR,&opt ,sizeof(opt));
bzero(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(PORT);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(listenfd,(struct sockaddr *) &server,sizeof(server)) == -1)
{
perror("Bind() error");
exit(1);
}
if(listen(listenfd,BACKLOG) == -1)
{
perror("listen() error.\n");
exit(1);
}
int len = sizeof(client);
if((connectfd = accept(listenfd,(struct sockaddr *)&client,&addrlen)) == -1)
{
perror("accept() error\n");
exit(1);
}
printf("You got a connection from client's ip is %s,port is%d\n",inet_ntoa(client.sin_addr),htons(client.sin_port));
send(connectfd,"Welcome\n",8,0);
close(connectfd);
close(listenfd);
}
[root@bogon Desktop]# 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询