Full Question:
Intuitively, there's no such direct command built into the programming language. Sockets need to be used but they are platform dependent.
Actually, there's no single C command or function to open a connection to a foreign host.
To do this, first, you need a socket that is provided by the socket() function. Then, you need to call connect() to establish the connection with the host. However, that requires that all host names have been resolved, so you may have had to call gethostbyname() or similar, to turn a hostname into an IP address.
Simple Example codes here. It is a TCP client implementation.
What is the C-language command for opening a connection with a foreign host over the internet?
Intuitively, there's no such direct command built into the programming language. Sockets need to be used but they are platform dependent.
Actually, there's no single C command or function to open a connection to a foreign host.
To do this, first, you need a socket that is provided by the socket() function. Then, you need to call connect() to establish the connection with the host. However, that requires that all host names have been resolved, so you may have had to call gethostbyname() or similar, to turn a hostname into an IP address.
Simple Example codes here. It is a TCP client implementation.
#include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> int main(){ int sock, bytes_recieved; char send_data[1024],recv_data[1024]; struct hostent *host; struct sockaddr_in server_addr; host = gethostbyname("127.0.0.1"); if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) { printf("Socket Error"); exit(1); } server_addr.sin_family = AF_INET; server_addr.sin_port = htons(5000); server_addr.sin_addr = *((struct in_addr *)host->h_addr); bzero(&(server_addr.sin_zero),8); if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) { perror("Connect"); exit(1); } while(1) { bytes_recieved=recv(sock,recv_data,1024,0); recv_data[bytes_recieved] = '\0'; if (strcmp(recv_data , "q") == 0 || strcmp(recv_data , "Q") == 0){ close(sock); break; } else printf("\nRecieved data = %s " , recv_data); printf("\nSEND (q or Q to quit) : "); gets(send_data); if (strcmp(send_data , "q") != 0 && strcmp(send_data , "Q") != 0) send(sock,send_data,strlen(send_data), 0); else { send(sock,send_data,strlen(send_data), 0); close(sock); break; } } return 0; }
What is the C-language command for opening a connection with a foreign host over the internet?