I'm trying to write a C program that listens on a port on my machine.
I'm running into a strange error.
Whenever I try to bind the socket to a fixed ip (either 127.0.0.1 or my actual IP) I get a "bind failed: Cannot assign requested address" error.
However when I pass INADDR_ANY to the bind as the address to bind to, it works.
These are the only two IPs I have so it can't be that the 0.0.0.0 works because of some other IP address I have available.
Here is the code:
#include<sys/types.h>
#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<errno.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int port = 1234; /* port number */
int rqst; /* socket accepting the request */
socklen_t alen; /* length of address structure */
struct sockaddr_in my_addr; /* address of this service */
struct sockaddr_in client_addr; /* client's address */
int sockoptval = 1;
int svc;
/* create a TCP/IP socket */
if ((svc = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("cannot create socket");
exit(1);
}
/* allow immediate reuse of the port */
setsockopt(svc, SOL_SOCKET, SO_REUSEADDR, &sockoptval, sizeof(int));
/* bind the socket to our source address */
memset((char*)&my_addr, 0, sizeof(my_addr)); /* 0 out the structure */
my_addr.sin_family = AF_INET; /* address family */
my_addr.sin_port = htons(port);
//my_addr.sin_addr.s_addr = htonl(INADDR_ANY); /* Works! */
my_addr.sin_addr.s_addr = htonl(inet_addr("127.0.0.1")); /* Fails! */
if (bind(svc, (struct sockaddr *)&my_addr, sizeof(my_addr)) < 0) {
perror("bind failed");
exit(1);
}
printf("Listening on %d\n", my_addr.sin_addr.s_addr);
/* set the socket for listening (queue backlog of 5) */
if (listen(svc, 5) < 0) {
perror("listen failed");
exit(1);
}
/* loop, accepting connection requests */
for (;;) {
while ((rqst = accept(svc, (struct sockaddr *)&client_addr, &alen)) < 0) {
/* we may break out of accept if the system call */
/* was interrupted. In this case, loop back and */
/* try again */
if ((errno != ECHILD) && (errno != ERESTART) && (errno != EINTR)) {
perror("accept failed");
exit(1);
}
}
/* the socket for this accepted connection is rqst */
}
}
The function inet_addr returns the address already in network order:
The inet_addr() function converts the Internet host address cp from
IPv4 numbers-and-dots notation into binary data in network byte order
So drop the htonl.
Related
I am having trouble getting my TCP/IP connection between my client and server working.
Here is the server code -
int main() {
int servSock; /* Socket descriptor for server */
int clntSock; /* Socket descriptor for client */
unsigned short echoServPort; /* Server port */
struct sockaddr_in echoServAddr; /* Local address */
struct sockaddr_in echoClntAddr; /* Local address */
pid_t processID; /* Process ID from fork()*/
unsigned int childProcCount = 0; /* Number of child processes */
unsigned int clntLen;
unsigned int recvMsgSize;
echoServPort = 22;
if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
printf("Socket failed");
}
echoServAddr.sin_family = AF_INET; //Internet address family
echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); //Any incoming interface
echoServAddr.sin_port = htons(echoServPort); // Local port
if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0){
printf("bind failed");
}
if (listen(servSock, MAXPENDING) < 0){
printf("listen() failed");
}
clntLen = sizeof(echoClntAddr);
if ((clntSock=accept(servSock,(struct sockaddr *)&echoClntAddr,&clntLen))<0){
printf("accept() failed");
}
if ((recvMsgSize = recv(clntSock, buf, 1024, 0)) < 0){
printf("recv() failed");
}
/* Send received string and receive again until end of transmission */
while (recvMsgSize > 0) { /* zero indicates end of transmission */
printf("%d", recvMsgSize);
if (send(clntSock, buf, recvMsgSize, 0) != recvMsgSize){
//printf(“send() failed”);
}
if ((recvMsgSize = recv(clntSock, buf, 1024, 0)) < 0){
//printf(“recv() failed”);
}
}
sleep(60);
}
}
return EXIT_SUCCESS;
}
And the client code, which is a CGI application.
int main(void) {
int servSock; /* Socket descriptor for server */
int clntSock; /* Socket descriptor for client */
unsigned short echoServPort; /* Server port */
struct sockaddr_in echoServAddr; /* Local address */
struct sockaddr_in echoClntAddr; /* Local address */
struct sockaddr_in {
__uint8_t sin_len;
sa_family_t sin_family;
in_port_t sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
/*pid_t processID; Process ID from fork()
unsigned int childProcCount = 0; Number of child processes
unsigned int clntLen;*/
//char echoservIP = "10.0.0.2";
printf("Content-type: text/html\n\n");
puts("<HTML>");
puts("<BODY>");
echoServPort = 22;
servSock = 22;
clntSock = 22;
puts("<br>");
if ((clntSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
printf("socket() failed");
}
echoServAddr.sin_family = AF_INET; //Internet address family
echoServAddr.sin_addr.s_addr = inet_addr("10.0.0.2"); //Server IP address
echoServAddr.sin_port = htons(echoServPort); //Server port
echoClntAddr.sin_addr.s_addr = inet_addr("10.0.0.1");
if (connect(clntSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0){
printf("connect() failed\n");
}
int clntLen;
clntLen = sizeof(echoClntAddr);
if ((clntSock=accept(servSock,(struct sockaddr *)&echoClntAddr,&clntLen))<0){
printf("accept() failed\n");
}
char echoString[4] = "helo";
int echoStringLen;
echoStringLen = strlen(echoString); //Determine input length
//Send the string to the server
if (send(clntSock, echoString, echoStringLen, 0) != echoStringLen){
printf("send() sent a different number of bytes than expected");
}
puts("<p>Hello <b>CGI</b</p>");
puts("</BODY>");
puts("</HTML>");
return EXIT_SUCCESS;
}
When debugging, the problem occurs on the client side at the line
if ((clntSock=accept(servSock,(struct sockaddr
*)&echoClntAddr,&clntLen))<0){
printf("accept() failed\n");
}
And at
if(send(clntSock, echoString, echoStringLen, 0) != echoStringLen){
printf("send() sent a different number of bytes than expected");
}
I get the output
<HTML>
<BODY>
<br>
accept() failed
send() sent a different number of bytes than expected<p>Hello
<b>CGI</b</p>
Need help fixing this!, thanks.
You don't need to call accept() on the client - you just need to connect.
And
char echoString[4] = "helo";
is wrong. It's not NUL-terminated. Just do
char echoString[] = "helo";
If accept fails you shouldn't be proceeding with other operations on socket like recv. TCP connections is not in place for you to proceed in data exchange between server and client. You need to handle error conditions with out fail.
On the client side you have a custom error message on send. That does not help. Usually, partial sends are not common. Hence your print `sent a different number of bytes than expected' can be misleading. You need to find the real reason.
Calling accept in client code is not needed. Its the server which accepts and clients the ones which connect
Use errno and perror like - perror("Accept Failed") on ALL of your system calls for easier debugging and remove custom prints
I have a simple C program that's supposed to listen for connections and start a new thread for each client that connects. The thread simply prints what messages it receives (for now). I followed two tutorials while making this.
It works, but I tried connecting and disconnecting repeatedly with netcat without sending any messages. Each time I connect, the program takes 8KB of memory, but it only releases 4KB when I disconnect. But I can't find the cause of the leak. It ends the thread and closes the socket every time the user disconnects. Here is all of the code involved:
void* clientFunction(void* arg) {
char receiveBuffer[RECEIVE_BUFFER_SIZE];
long receiveSize;
int clntSocket = * ((int*) arg);
while (true) {
//receive messages
receiveSize = recv(clntSocket, receiveBuffer, RECEIVE_BUFFER_SIZE, 0);
if (receiveSize <= 0) {
close(clntSocket);
return NULL;
}
printf("Received message: %s", receiveBuffer);
memset(&receiveBuffer, 0, sizeof(receiveBuffer));
}
return 0;
}
int main(int argc, const char * argv[]) {
//FOR LISTENING SOCKET =====
int servSock; /* Socket descriptor for server */
int clntSock; /* Socket descriptor for client */
struct sockaddr_in serverAddress; /* Local address */
struct sockaddr_in clientAddress; /* Client address */
unsigned int clntLen; /* Length of client address data structure */
// =======
/* Create socket for incoming connections */
if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
printf("Socket creation failed!\n");
return SOCKET_ERROR;
}
memset(&serverAddress, 0, sizeof(serverAddress)); /* Zero out structure */
serverAddress.sin_family = AF_INET; /* Internet address family */
serverAddress.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
serverAddress.sin_port = htons(PORT); /* Local port */
if (bind(servSock, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0) {
printf("Socket binding failed!\n");
return SOCKET_ERROR;
}
if (listen(servSock, MAXPENDING) < 0) {
printf("Socket listening failed!\n");
return SOCKET_ERROR;
}
isListening = true;
int* arg = &clntSock;
while (isListening) { //should have a timer?
/* Set the size of the in-out parameter */
clntLen = sizeof(clientAddress);
/* Wait for a client to connect */
if ((clntSock = accept(servSock, (struct sockaddr *) &clientAddress, &clntLen)) >= 0) { //??????
/* clntSock is connected to a client! */
pthread_t clientThread;
pthread_create(&clientThread, NULL, &clientFunction, (void*) arg);
}
}
return 0;
}
I put in pthread_detach(pthread_self()) right after the socket closing line, and it doesn't have the problem anymore. – sudo
I need my server to broadcast a message (not that it matters but it contains its IP/port info). What I have currently is the working server broadcast, code below. I'm not sure about setting up the client because usually I would use the IP/port of the server which the client doesn't have until it receives the broadcast. The client never receives anything. Can someone tell me what is wrong.
Server:
struct sockaddr_in server, bcast;
int sockfd;
int blen = sizeof(bcast);
int svrlen = sizeof(server);
char buf[BUFLEN];
if((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1){
printf("Socket error.\n");
exit(1);
}
int broadcastPermission = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (void *)&broadcastPermission,sizeof(broadcastPermission)) < 0){
printf("Error setting socket options.");
}
memset(&bcast, 0, sizeof(bcast));
bcast.sin_family = AF_INET;
bcast.sin_port = htons(PORT);
bcast.sin_addr.s_addr = htonl(INADDR_ANY);
string bcastIP = BCASTIP;
if(inet_aton("255.255.255.255", &bcast.sin_addr) == 0){
printf("Broadcast Address error.");
exit(1);
}
if (bind(sockfd, (struct sockaddr*)&server, sizeof(server)) == -1){
printf("Port error.\n");
exit(1);
}
fflush(stdout);
if(int bytes = sendto(sockfd, ipinfo, sizeof(ipinfo), 0, (struct sockaddr*)&bcast, blen) == -1){
printf("Broadcast send error.");
}
else{
printf("Sent"):
}
Client:
struct sockaddr_in server;
int sockfd;
int bytes;
int svrlen = sizeof(server);
char buf[BUFLEN]
if((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1){
printf("Socket error.\n");
exit(1);
}
memset((char *)&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(BPORT);
server.sin_addr.s_addr = htonl(INADDR_ANY);
while(1){
printf("Waiting for broadcast...\n\n");
fflush(stdout);
memset(buf,0,BUFLEN);
bytes = recvfrom(sockfd, buf, BUFLEN, 0, (struct sockaddr*)&server, (socklen_t*)&svrlen);
printf("Received");
}
Your client is not calling bind() on the socket before trying to receive data.
http://cs.baylor.edu/~donahoo/practical/CSockets/code/BroadcastReceiver.c shows the following example which you may find helpful:
void DieWithError(char *errorMessage); /* External error handling function */
int main(int argc, char *argv[])
{
int sock; /* Socket */
struct sockaddr_in broadcastAddr; /* Broadcast Address */
unsigned short broadcastPort; /* Port */
char recvString[MAXRECVSTRING+1]; /* Buffer for received string */
int recvStringLen; /* Length of received string */
if (argc != 2) /* Test for correct number of arguments */
{
fprintf(stderr,"Usage: %s <Broadcast Port>\n", argv[0]);
exit(1);
}
broadcastPort = atoi(argv[1]); /* First arg: broadcast port */
/* Create a best-effort datagram socket using UDP */
if ((sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
DieWithError("socket() failed");
/* Construct bind structure */
memset(&broadcastAddr, 0, sizeof(broadcastAddr)); /* Zero out structure */
broadcastAddr.sin_family = AF_INET; /* Internet address family */
broadcastAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
broadcastAddr.sin_port = htons(broadcastPort); /* Broadcast port */
/* Bind to the broadcast port */
if (bind(sock, (struct sockaddr *) &broadcastAddr, sizeof(broadcastAddr)) < 0)
DieWithError("bind() failed");
/* Receive a single datagram from the server */
if ((recvStringLen = recvfrom(sock, recvString, MAXRECVSTRING, 0, NULL, 0)) < 0)
DieWithError("recvfrom() failed");
recvString[recvStringLen] = '\0';
printf("Received: %s\n", recvString); /* Print the received string */
close(sock);
exit(0);
}
I need my server to broadcast a message (not that it matters but it contains its IP/port info).
That sounds a lot like service discovery. You should really use the standard mDNS/Zeroconf protocol for that. You can use the Avahi library for that (or use the Avahi service on Linux or Zeroconf on MacOS X).
i have two code here for a UDP chat with a broadcasting mechanism where the server can broadcast a message to all clients simultaneously
Server code...
#include<stdio.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
int main(int argc, char *argv[] )
{
struct sockaddr_in client,server;
int s,n;
char b1[100],b2[100];
s=socket(AF_INET,SOCK_DGRAM,0);
server.sin_family=AF_INET;
server.sin_port=htons(2000);
server.sin_addr.s_addr=inet_addr("127.0.0.1");
bind(s,(struct sockaddr *)&server,sizeof(server));
printf("\nServer ready,waiting for client....\n");
n=sizeof(client);
int sock; /* Socket */
struct sockaddr_in broadcastAddr; /* Broadcast address */
char *broadcastIP; /* IP broadcast address */
unsigned short broadcastPort; /* Server port */
char *sendString; /* String to broadcast */
int broadcastPermission; /* Socket opt to set permission to broadcast */
unsigned int sendStringLen; /* Length of string to broadcast */
if (argc < 4) /* Test for correct number of parameters */
{
fprintf(stderr,"Usage: %s <IP Address> <Port> <Send String>\n", argv[0]);
exit(1);
}
broadcastIP = argv[1]; /* First arg: broadcast IP address */
broadcastPort = atoi(argv[2]); /* Second arg: broadcast port */
sendString = argv[3]; /* Third arg: string to broadcast */
/* Create socket for sending/receiving datagrams */
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
broadcastPermission = 1;
while(1)
{
recvfrom(s,b1,sizeof(b1),0,(struct sockaddr *) &client,&n);
if(!(strcmp(b1,"end")))
break;
printf("\nClient:%s",b1);
printf("\nServer:");
gets(b2);
sendto(s,b2,sizeof(b2),0,(struct sockaddr *) &client,n);
broadcastPermission = 1;
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (void *) &broadcastPermission,sizeof(broadcastPermission));
/* Construct local address structure */
//memset(&broadcastAddr, 0, sizeof(broadcastAddr)); /* Zero out structure */
broadcastAddr.sin_family = AF_INET; /* Internet address family */
broadcastAddr.sin_addr.s_addr = inet_addr(broadcastIP);/* Broadcast IP address */
broadcastAddr.sin_port = htons(broadcastPort); /* Broadcast port */
sendStringLen = strlen(sendString);
for (;;) /* Run forever */
{
/* Broadcast sendString in datagram to clients every 3 seconds*/
sendto(sock, sendString, sendStringLen, 0, (struct sockaddr *) &broadcastAddr, sizeof(broadcastAddr));
// DieWithError("sendto() sent a different number of bytes than expected");
//sleep(3); /* Avoids flooding the network */
}
}
}
Client code...
#include<stdio.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define MAXRECVSTRING 255
int main(int argc , char argv[])
{
struct sockaddr_in client,server;
int s,n;
char b1[100],b2[100];
s=socket(AF_INET,SOCK_DGRAM,0);
server.sin_family=AF_INET;
server.sin_port=htons(2000);
server.sin_addr.s_addr=inet_addr("127.0.0.1");
printf("\nClient ready....\n");
n=sizeof(server);
int sock; /* Socket */
struct sockaddr_in broadcastAddr; /* Broadcast Address */
unsigned short broadcastPort; /* Port */
char recvString[MAXRECVSTRING+1]; /* Buffer for received string */
int recvStringLen; /* Length of received string */
if (argc != 2) /* Test for correct number of arguments */
{
fprintf(stderr,"Usage: %s <Broadcast Port>\n", argv[0]);
exit(1);
}
printf("\nClient ready…11111.\n");
broadcastPort = htons(argv[1]); /* First arg: broadcast port */
printf("\nClient ready….1\n");
/* Create a best-effort datagram socket using UDP */
if(sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)<0)
printf("no sock created");
printf("\nClient ready….2\n");
while(1)
{
printf("\nClient:");
gets(b2);
sendto(s,b2,sizeof(b2),0,(struct sockaddr *) &server,n);
if(strcmp(b2,"end")==0)
break;
recvfrom(s,b1,sizeof(b1),0,NULL,NULL);
printf("\nServer:%s",b1);
broadcastAddr.sin_family = AF_INET; /* Internet address family */
broadcastAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
broadcastAddr.sin_port = htons(broadcastPort); /* Broadcast port */
/* Bind to the broadcast port */
bind(sock, (struct sockaddr *) &broadcastAddr, sizeof(broadcastAddr));
/* Receive a single datagram from the server */
recvStringLen = recvfrom(sock, recvString, MAXRECVSTRING, 0, NULL, 0);
recvString[recvStringLen] = '\0';
printf("Received: %s\n", recvString); /* Print the received string */
}
close(sock);
}
These code run without any error but when i send a string from client to the server the server is unable to receive the string and vice versa.
If someone could help me out as to why this is happening.
i am running both the server and client on the same system in different terminal windows..hence the local host address
Some platforms, e.g. Windows, won't receive broadcasts unless the socket is bound to INADDR_ANY, i.e. 0.0.0.0.
To start with:
server.sin_port=2000;
You forget to make this network-order.
In your server code:
The socket is not bound to any IP address. Although it broadcasts the message and the client receives; the vice-versa won't work.
Thus, bind your server and client side sockets to 2 different IP addresses.
When the server broadcasts the message, use appropriate broadcast address (see the subnet of the server-client IP) in the sendto function.
I have a C program that I am trying to implement a daemon process that acts as a general TCP proxy server. I believe I have completed mostly everything correct but there is a while loop that I cannot figure out. Below is my code and I will put *** around what I am having trouble with.
Program descriptions
(1) The daemon listens for TCP connections on a specified port number.
(2) When a new client initiates a TCP connection request, the daemon accepts the request and
establishes a new TCP connection with the new client.
(a) The daemon forks a child process that is dedicated to handling the new client.
(b) The child process establishes a new TCP connection to a pre-assigned port on the actual
targeted server.
(c) The child process falls into a loop in which it acts as an intermediator exchanging data
(reading/writing or writing/reading) between the client and the targeted server.
(3) Once a child has been forked, the daemon process resumes listening for additional TCP
connections from other clients.
#ifndef unix
#define closesocket close
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdlib.h>
#include <stdio.h>
#endif
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define PROTOPORT 5100 /* default protocol port number */
#define QLEN 6 /* size of request queue */
int visits = 0;
int argc;
char *argv[];
int main() // works as "server" side
{
struct hostent *ptrh; /* pointer to a host table entry */
struct protoent *ptrp; /* pointer to a protocol table entry */
struct sockaddr_in sad; /* structure to hold server's address */
struct sockaddr_in cad; /* structure to hold client's address */
int sd0, sd1; /* socket descriptors */
int port; /* protocol port number */
int addrlen; /* length of address */
pid_t pid;
memset((char *)&sad, 0, sizeof(sad)); /* clear sockaddr structure */
sad.sin_family = AF_INET; /* set family to Internet */
sad.sin_addr.s_addr = INADDR_ANY; /* set the local IP address(not specify, reserved */
if(argc > 1){
port = atoi(argv[1]);
}
else port = PROTOPORT; /* use the specified port number */
if (port > 0) /* test for illegal value */
sad.sin_port = htons((u_short)port);
else
{ /* print error message and exit */
fprintf(stderr,"bad port number %s\n", argv[1]);
exit(1);
}
/* Map TCP transport protocol name to protocol number */
if( ((int)(ptrp = getprotobyname("tcp"))) == 0) {
fprintf(stderr, "cannot map \"tcp\" to protocol number");
exit(1);
}
/* Create a socket */
sd0 = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
if(sd0 < 0){
fprintf(stderr, "socket creation failed\n");
exit(1);
}
/* Bind a local address to the socket */
// bind()
if (bind(sd0, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
fprintf(stderr,"bind failed\n");
exit(1);
}
/* Listen at the port */
// listen()
/* Specify size of request queue */
if (listen(sd0, QLEN) < 0) {
fprintf(stderr,"listen failed\n");
exit(1);
}
/* Main server loop - accept and handle requests */
while (1)
{
// accept request
addrlen = sizeof(cad);
sd1 = accept(sd0, (struct sockaddr *)&cad, &addrlen);
// fork a process
pid = fork();
if(pid == 0) // child process
{
//close oldsocket;
close(sd0);
HandleClientConnection(sd1);
break;
}
else /*parant process */
{
close(sd1);
continue;
}
}
return 0;
}
// implement "HandleClientConnection(new socket1)" - works as "client" side
HandleClientConnection(newsocket1)
{
// general socket settings at the client side
struct hostent *ptrh; /* pointer to a host table entry */
struct protoent *ptrp; /* pointer to a protocol table entry */
struct sockaddr_in sad; /* structure to hold an IP address */
int newsocket2; /* socket descriptor */
int port; /* protocol port number */
char *host; /* pointer to host name */
int n, n2; /* number of characters read */
char buf[1000]; /* buffer for data from the server */
int i;
memset((char *)&sad,0,sizeof(sad)); /* clear sockaddr structure */
sad.sin_family = AF_INET; /* set family to Internet */
***while(1) /* get the real server's IP addr from "GET" command */
{
// read to buffer and compare, such as
if(strncmp("GET", buf[i-1], 3) == 0 || strncmp("CONNECT", buf[i-1], 7) == 0)
{
while(1)
{
//...; // read more
if(strncmp("Host", buf[i-1], 4) == 0)
{
//...;
printf("\nfound the host name.\n");
//...;
}
}
break;
}
}***
/* Convert real host name to equivalent IP address and copy to sad. */
// gethostbyname();
ptrh = gethostbyname(host);
if ( ((char *)ptrh) == NULL )
{
fprintf(stderr,"invalid host: %s\n", host);
exit(1);
}
memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_length);
/* Map TCP transport protocol name to protocol number. */
if ( ((int)(ptrp = getprotobyname("tcp"))) == 0) {
fprintf(stderr, "cannot map \"tcp\" to protocol number");
exit(1);
}
/* Create a newsocket2. */
// socket();
newsocket2 = socket(PF_INET, SOCK_STREAM, ptrp->p_proto);
if (newsocket2 < 0) {
fprintf(stderr, "socket creation failed\n");
exit(1);
}
/* Connect the socket to the specified server. */
// connect()
if (connect(newsocket2, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
fprintf(stderr,"connect failed\n");
exit(1);
}
// Repeatedly read data from client (newsocket1) and write to server' side (newsocket2)
n = recv(newsocket1, buf, sizeof(buf), 0);
while (n > 0) {
write(newsocket2,buf,n);
n = recv(newsocket1, buf, sizeof(buf), 0);
}
// Repeatedly read data from server' side (newsocket2) and write to client (newsocket1).
n2 = recv(newsocket2, buf, sizeof(buf), 0);
while (n2 > 0) {
write(newsocket1,buf,n2);
n2 = recv(newsocket2, buf, sizeof(buf), 0);
}
// Close the newsocket2
close(newsocket2);
}