简体   繁体   中英

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?

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM