我正在开发一个涉及套接字编程的C程序,基本上我正在尝试编写一个简单的HTTP服务器,我对此很菜鸟,并且我遇到了绑定问题。我编写了以下代码,但在绑定过程中遇到错误。我检查了代码,似乎找不到问题所在。谁能帮我找出问题所在吗?
当我运行程序时,我得到这个输出
这是我的代码
#include <stdio.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#define PORT "4390"
int main(){
int status;
struct addrinfo hints, *res;
int sockfd;
memset(&hints,0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if((status = getaddrinfo("localhost",PORT,&hints,&res) != 0)){
fprintf(stderr,"getaddrinfo error: %s\n",gai_strerror(status));
}
if((sockfd = socket(res->ai_family,res->ai_socktype,0) == -1)){
fprintf(stderr,"socket error %s\n",gai_strerror(sockfd));
}
int bindstatus;
if((bindstatus = bind(sockfd,res->ai_addr,res->ai_addrlen) == -1)){
fprintf(stderr,"bind error %s\n", gai_strerror(bindstatus));
}
printf("%d\n",bindstatus);
return 0;
}
主要问题是由于在没有正确理解运算符优先级的情况下尝试编写紧凑的代码而引起的。除此之外还有一些其他错误。
拍摄这一部分:
if((sockfd = socket(res->ai_family,res->ai_socktype,0) == -1)){
...report error
}
您在这里尝试做的是
sockfd = socket(res->ai_family,res->ai_socktype,0);
if (sockfd == -1) {
...report error
}
你所做的是
sockfd = ( socket(res->ai_family,res->ai_socktype,0) == -1 );
if (sockfd) { ...
因此,
sockfd
不会是 sockfd
,而是可能为 0,因为 0 表示 false,而 false 是 ==
返回的内容(文件描述符)与 socket
之间进行 -1
比较的结果。
因此
bind
稍后将被调用,且 sockfd
为 0,这不是一个有效的套接字。因此绑定将会失败。在带有 bind
的代码中,您再次犯了同样的优先级错误。
除此之外,
gai_strerror
期望的是errno
,而不是socket
或bind
调用的结果。