【问题标题】:C sockets: getsocketnane ip address is always 0.0.0.0C套接字:getsocketnane ip地址始终为0.0.0.0
【发布时间】:2018-11-13 12:33:18
【问题描述】:

嗨,我正在用 c 编写一个网络客户端,我正在使用 getsocketname 函数返回我创建的套接字的 IP 和端口,但由于某种原因,IP 总是返回为 0.0.0.0 这里是代码:

#include <stdio.h> //include standard input/output library
#include <stdlib.h> //include standard libraries
#include <string.h> //include string headers 
#include <unistd.h> //add definitions for constansts and functions 
#include <sys/types.h> // include definitions for different data types
#include <sys/socket.h> //include socket support
#include <netinet/in.h> //define internet protocol functions
#include <arpa/inet.h> //define internet protocol functions
#include "Practical.h" //include practical header file

int main(int argc, char *argv[]) {

char myIP[16];
unsigned int myPort;
struct sockaddr_in server_addr,myaddr;

  if (argc < 3 || argc > 4) // Test for correct number of arguments
    DieWithUserMessage("Parameter(s)",
        "<Server Address> <Echo Word> [<Server Port>]");

  char *servIP = argv[1];     // First arg: server IP address (dotted quad)
  char *echoString = argv[2]; // Second arg: string to echo

  // Third arg (optional): server port (numeric).  7 is well-known echo port
  in_port_t servPort = (argc == 4) ? atoi(argv[3]) : 7;  //21



 // Create a reliable, stream socket using TCP  //23
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);//this block of code creates a reliable tcp stream socket and checks what the returned integer is from the socket function, the returned function will give a integer that descibes the socket. if this is 0 then kill the socket and show the user an error message.
  if (sock < 0)
    DieWithSystemMessage("socket() failed"); //26

  // Construct the server address structure //28
  struct sockaddr_in servAddr;            // Server address
  memset(&servAddr, 0, sizeof(servAddr)); // Zero out structure
  servAddr.sin_family = AF_INET;          // IPv4 address family
  // Convert address
  int rtnVal = inet_pton(AF_INET, servIP, &servAddr.sin_addr.s_addr);
  if (rtnVal == 0)
    DieWithUserMessage("inet_pton() failed", "invalid address string");
  else if (rtnVal < 0)
    DieWithSystemMessage("inet_pton() failed");
  servAddr.sin_port = htons(servPort);    // Server port
  myaddr.sin_addr.s_addr = INADDR_LOOPBACK;

bzero(&myaddr,sizeof(myaddr));
int len = sizeof(myaddr);
getsockname(sock,(struct sockaddr *) &myaddr, &len);
inet_ntop(AF_INET, &myaddr.sin_addr, myIP, sizeof(myIP));
myPort = ntohs(myaddr.sin_port);

printf("local ip address : %s\n", myIP);
printf("local port: %u\n", myPort);

  // Establish the connection to the echo server
  if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
    DieWithSystemMessage("connect() failed"); 

  size_t echoStringLen = strlen(echoString); // Determine input length //44

  // Send the string to the server
  ssize_t numBytes = send(sock, echoString, echoStringLen, 0);
  if (numBytes < 0) //sending string to server, number of bytes of the message is equal to return value of send function, if the number of bytes is less than 0 then do not send and say to user that the send failed
    DieWithSystemMessage("send() failed");
  else if (numBytes != echoStringLen)
    DieWithUserMessage("send()", "sent unexpected number of bytes"); //51

// if the number of bytes is not equal to the input length of the string parsed as an argument then die with the message to the user saying sent unexpected number of bytes.

  // Receive the same string back from the server  //53
  unsigned int totalBytesRcvd = 0; // Count of total bytes received
  fputs("Received: ", stdout);     // Setup to print the echoed string
  while (totalBytesRcvd < echoStringLen) {
    char buffer[BUFSIZE]; // I/O buffer
    /* Receive up to the buffer size (minus 1 to leave space for
     a null terminator) bytes from the sender */
    numBytes = recv(sock, buffer, BUFSIZE - 1, 0);
    if (numBytes < 0)
      DieWithSystemMessage("recv() failed");
    else if (numBytes == 0)
      DieWithUserMessage("recv()", "connection closed prematurely");
    totalBytesRcvd += numBytes; // Keep tally of total bytes
    buffer[numBytes] = '\0';    // Terminate the string!
    fputs(buffer, stdout);      // Print the echo buffer

  }

  fputc('\n', stdout); // Print a final linefeed //70


  close(sock);
  exit(0);
}
//closing off connections to clean up data left over.

返回的端口号也总是 0,我将 myaddr 结构的地址分配为环回地址,所以我相信它应该返回 127.0.0.1 作为 IP 但它不是,我有点新套接字编程,所以我的逻辑可能不完美,我只是看不出这里有什么问题

【问题讨论】:

    标签: c sockets networking


    【解决方案1】:

    表示socket还没有绑定到本地地址。

    您需要在绑定后获取本地地址,这会在connect 调用中自动发生。

    【讨论】:

    • 您好,感谢您的评论。如果我在调用连接函数后移动代码以获取本地 IP,则 IP 地址将打印为空白,端口为 0
    • 我修好了,只是我太笨了。我试图在调用 getsockname 之前打印出这些值。感谢您的帮助!
    猜你喜欢
    • 2012-11-03
    • 2011-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多