好的 - 所以我正在尝试使用 C++ 为 IPv6 运行一个受欢迎的套接字。问题是每次我启动程序时它监听的端口似乎都会改变。
#include <iostream>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <arpa/inet.h>
int main(int argc, char *argv[]){
//Setting up the serverAddr:
struct sockaddr_in6 serverAddr;
memset((char *)&serverAddr, 0, sizeof(sockaddr_in6));
serverAddr.sin6_family = AF_INET6; // IP6 is best current practise.
serverAddr.sin6_addr = in6addr_any; // Don't care for interfaces.
serverAddr.sin6_port = htons(7979); // FIXME change port later.
//Opening the welcomeSocket:
std::cout << "Opening socket:\t";
int welcomeSocket = socket(AF_INET6, SOCK_STREAM, 0);
if(welcomeSocket < 0){
std::cout << "[FAIL]" << std::endl;
return 1;
}else{
std::cout << "[ OK ]" << std::endl;
}
//Listening for clients:
while(welcomeSocket >= 0){
std::cout << "Listening for connections…" << std::endl;
listen(welcomeSocket, 1);
struct sockaddr_in6 clientAddr;
memset((char *)&clientAddr, 0, sizeof(sockaddr_in6));
int clientAddrLength = sizeof(clientAddr);
int clientSocket = accept(welcomeSocket, (struct sockaddr*) &clientAddr, (socklen_t*) &clientAddrLength);
char caddr[INET6_ADDRSTRLEN]; //caddr is not lisp here.
inet_ntop(AF_INET6, &clientAddr, caddr, INET6_ADDRSTRLEN);
std::cout << "Request from '" << caddr << "'" << std::endl;
shutdown(clientSocket, SHUT_RDWR);
clientSocket = -1;
shutdown(welcomeSocket, SHUT_RDWR);
welcomeSocket = -1;
}
return 0;
}
我通过 g++ server.cpp -o server 编译代码,当我运行 ./server 时,我得到以下输出:
$ ./server
Opening socket: [ OK ]
Listening for connections…
Request from 'a00:c158::'
为了测试我运行 nmap 的代码:
$ nmap -6 -p 1-65535 ::1
Starting Nmap 5.21 ( http://nmap.org ) at 2012-06-09 16:43 CEST
Nmap scan report for ip6-localhost (::1)
Host is up (0.00023s latency).
Not shown: 65532 closed ports
PORT STATE SERVICE
22/tcp open ssh
631/tcp open ipp
56160/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 1.41 seconds
我想我忽略了一些简单的事情。