Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Why can't I access my server from outside localhost?

I've been working with socket programming lately; and I'm currently making a server that listens on a port for incoming connections, then once it gets one, reads in a string and places it in a file.

It all works fine when I'm telneting to the running server from localhost, but when I attempt to access it from anywhere else, it acts as though it doesn't exist. Nmap doesn't show that particular open port -- from either the localhost or the remote host. It only works through telnet on localhost.

The function's code is here. (Pastebin) I know it's a mess, I'm still pretty unfamiliar with network programming. There really aren't any good in-depth tutorials that show you everything you need to know. I guess I'll have to buy a book...

like image 222
screennameless Avatar asked Oct 19 '11 01:10

screennameless


People also ask

How can I access localhost from anywhere?

http://localtunnel.me. http://localhost.run.

What reasons might cause a server to refuse a connection request from a client?

The two most common causes of this are: Misconfiguration, such as where a user has mistyped the port number, or is using stale information about what port the service they require is running on. A service error, such as where the service that should be listening on a port has crashed or is otherwise unavailable.


1 Answers

Your code is calling

    if(bind(*sock, b->ai_addr, b->ai_addrlen) == -1) {

where b is based on the result of calling getaddrinfo. This probably doesn't contain exactly what you want. It looks like cliaddr already contains the correct data to pass to bind(), so use that instead:

    if (bind(*sock, (struct sockaddr *)&cliaddr, sizeof(cliaddr)) {

I'm not sure what getaddrinfo() might return for you, but it sounds from your description like it might be providing the address 127.0.0.1 (which is localhost). If you bind() only to the localhost interface, then that's the only address that will respond to request to connect. If you bind to INADDR_ANY, then all interfaces will respond to requests for connection.

For a simple socket listening program, you probably don't need the call to getaddrinfo() at all.

like image 119
Greg Hewgill Avatar answered Sep 23 '22 05:09

Greg Hewgill