C套接字:getsocketnane ip地址始终为0.0.0.0

时间:2018-11-13 12:33:19

标签: c sockets networking

嗨,我正在用c编程一个网络客户端,并且我正在使用getsocketname函数返回我创建的套接字的IP和端口,但是由于某些原因,该IP始终返回为0.0.0.0,这是代码:< / p>

#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,但不是,我有点新进行套接字编程,因此我的逻辑可能并不完美,我只是看不到这里有什么问题

1 个答案:

答案 0 :(得分:0)

这意味着套接字尚未绑定到本地地址。

绑定后,您需要获取本地地址 ,该地址会通过connect调用自动发生。