BossySmaxx
BossySmaxx

Reputation: 37

how to provide custom IP to sockets in C?

How can I give a custom ip to my program, I've built a chat app, not the whatsapp, jus cui based simple chat app, coz imma beginner, I've used inet_addr() function, but it says can't assign ip, it only allows localhost IPs(127.0.0.1 to 127.0.0.254), can you please tell me, what should I do. please…. here's my code : -

here's the problematic code :-

struct sockaddr_in serv_addr,cli_addr;
int serv_socket,cli_socket,cli_len = sizeof(cli_addr);
char buff[256];

serv_addr.sin_port = htons(32000);
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
serv_addr.sin_family = AF_INET;

if the above code didn't helped then, here's my link maybe you will find something interesting there, and please gimme a solution, I really need help please.......

https://github.com/BossySmaxx/C-HatAPP.git

Upvotes: 1

Views: 541

Answers (1)

Alex Hoffmann
Alex Hoffmann

Reputation: 367

Going from the documentation of bind and then the appropriate protocol ip.

When a process wants to receive new incoming packets or connections, it should bind a socket to a local interface address using bind(2). In this case, only one IP socket may be bound to any given local (address, port) pair.

You will need to provide your serv_add with a valid ip address of your host's interface(s).

You can do something like this to obtain a valid ip

char *ip; 
char buffer[256]; 
struct hostent *he; 
int hostname;

hostname = gethostname(buffer, sizeof(buffer)); 
he = gethostbyname(buffer); 

// ip string
ip = inet_ntoa(*((struct in_addr*) he->h_addr_list[0])); 

Upvotes: 2

Related Questions