re3el re3el - 1 month ago 9
C Question

Unable to copy ip address from string to sockaddr_in

I am trying to copy an IP address from a string to struct sockaddr_in but somehow there's some error popping up.

#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;
}


The output of the above code shows:

ip: 128.10.25.102, strlen:13
Server IP: 0.0.0.0


There is some error in copying the value from
ip
string which I am unable to figure out. What could be the reason?

Answer

This is the problem in your pastebin code:

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

(Trying to append null terminator but using strlen, which itself depends on a null terminator to be present).

Here is the fix:

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