【发布时间】:2016-02-09 12:38:44
【问题描述】:
代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
// #include <thread>
#include <arpa/inet.h>
#include <iostream>
using namespace std;
#define PORT 8888
#define BACKLOG 5
int main(int argc, char const *argv[]) {
int status;
struct addrinfo hints,
*res,
*temp;
char ipstr [INET6_ADDRSTRLEN];
int socket_fd;
memset (&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; // Allows both IPv4 and IPv6
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // Allows automatic fill-up of IP (allows using localhost)
if ((status = getaddrinfo (NULL , "8000", &hints, &res)) != 0 ) {
cout << "[-] Error: " << gai_strerror (status) << endl;
exit (EXIT_FAILURE);
}
socket_fd = socket (res->ai_family, res->ai_socktype, res->ai_protocol);
if (socket_fd == -1) {
cout << "[-] Error : Socket couldn't be created" << endl;
exit (EXIT_FAILURE);
}
if (bind (socket_fd, res->ai_addr, res->ai_addrlen) == -1 ) {
cout << "[-] Error: Failed to bind to port" << endl;
exit (EXIT_FAILURE);
}
if (connect (socket_fd, res->ai_addr, res->ai_addrlen) == -1) {
cout << "[-] Error: Failed to connect to remote user" << endl;
exit (EXIT_FAILURE);
}
freeaddrinfo (res); // free the linked list returned by getaddrinfo ()
return 0;
}
代码正在返回:
[-] 错误:绑定端口失败
无论我在getaddrinfo() 的第一个参数(使其监听localHost)上设置NULL 还是提供一些地址,它都无法将端口绑定到套接字。正如我通过更改端口的值尝试过的那样,端口可用。代码有什么问题?
【问题讨论】:
-
当一个函数像 e.g.
bind失败,它设置errno。使用例如strerror得到一个可打印的错误字符串并打印出来,你就会知道为什么调用失败了。你不应该让任何人告诉你这个,它是right there in the manual page。 -
也许使用
netstat -a来查看该端口是否在使用中 -
谢谢。猜猜我正在测试的端口正被其他应用程序使用