1

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

Alex Hoffmann
  • 355
  • 4
  • 20
BossySmaxx
  • 37
  • 7
  • 3
    "I've used inet_addr() function, but it says can't assign ip," Please show the exact error message and the code that causes it. – Code-Apprentice Nov 19 '19 at 21:28
  • You can only use an IP that's assigned to one of your network interfaces. – Barmar Nov 19 '19 at 21:28
  • dude this program is running well, But I want to assign it an IP so I and my friend can use it to chat over the internet, still it is running only on localhost............ – BossySmaxx Nov 20 '19 at 13:13

1 Answers1

2

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])); 
Alex Hoffmann
  • 355
  • 4
  • 20