Adam
Adam

Reputation: 2552

Connect to an IP address using connect() function - socket programming

I'm currently working on a client/server program. When I use a client and a server code running on the same machine, I can easily connect the client to the server using the connect() function (through "localhost").

However, the next step I would like to accomplish is by connecting to an external device. Except, this time, I would like to connect directly to its IP address. Does anyone know how I can integrate the IP address of a device in the connect() function?

Upvotes: 0

Views: 2874

Answers (2)

Jayesh Bhoi
Jayesh Bhoi

Reputation: 25875

Information like IP address of the remote host and its port is bundled up in a structure ( ex. struct sockaddr_in serv_addr; ) and a call to function connect() is made which tries to connect this socket with the socket (IP address and port) of the remote host.

So you can give you remote host IP as folllows

 //Name the socket as agreed with server.
   serv_addr.sin_family = AF_INET;
   serv_addr.sin_addr.s_addr = inet_addr("10.10.1.34"); //you can give your server IP here
   serv_addr.sin_port = htons(PORT); //your port here

OR you can bind to any PORT as follows

  /* bind any port number */
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  serv_addr.sin_port = htons(0);

Upvotes: 2

Dries
Dries

Reputation: 1005

You should be able to fill int the IP address in the connect function like you filled in the "localhost". Instead of giving it the name you can directly input the IP (as far as I know).

the name Localhost is actually also an IP: 127.0.0.1 if you didn't know and your network changes this for you so you don't have to memorize numbers.

As for the actual connection: be sure to open up the ports you use for your server on the modem of the network it's in. Otherwise your client won't be able to connect to it.

I hope this is what you needed to know.

Upvotes: 1

Related Questions