簡體   English   中英

無法將IP地址從字符串復制到sockaddr_in

[英]Unable to copy ip address from string to sockaddr_in

我正在嘗試將IP地址從字符串復制到struct sockaddr_in,但不知何故彈出了錯誤。

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>

int main(void)
{
    char *buf = "128.10.25.102:30015";
    char ip[30];
    struct sockaddr_in s1_addport;
    int i = 0;

    while (buf[i] != ':') i++;
    strncpy(ip, &buf[0], i);
    ip[strlen(ip)] = '\0';

    printf("ip: %s, strlen:%zu\n",ip,strlen(ip));
    inet_aton(ip,&s1_addport.sin_addr);
    printf("Server IP: %s\n",inet_ntoa(s1_addport.sin_addr));
    return 0;
}

上面代碼的輸出顯示:

ip: 128.10.25.102, strlen:13  
Server IP: 0.0.0.0

ip字符串復制值時出現錯誤,我無法弄清楚。 可能是什么原因?

這是您的pastebin代碼中的問題:

ip[strlen(ip)]='\0';

(嘗試附加null終止符,但使用strlen本身依賴於存在的null終止符)。

解決方法是:

....
while(buf[i]!=':')
    i++;
strncpy(ip,&buf[0],i);
ip[i]='\0';
puts(ip);
....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM