C ++ IPv6端口问题

时间:2012-06-09 14:47:42

标签: c++ networking port ipv6

好的 - 所以我正在尝试使用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

我想我忽略了一些简单的事情。

1 个答案:

答案 0 :(得分:3)

是的,我想你也是。在使用套接字进行任何操作之前,还需要进行一些其他调用。如果您想成为服务器,则必须调用bind()来设置本地地址,并listen()通知操作系统这是服务器。然后你可以使用接受。有时候会有点痛苦。