Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
How can you modify your server code to make it accept any port numbers instead of just one which is the one you predefined?
+2
−2
Is there any way where I can modify the original server code so that it accepts any port number instead of the predefined one (i.e., port number 8989)? Port number will be entered in the command line when testing the Server1.exe as follows:
start server 8989
(also the main function parameters holds the port the command line arguments)
#include<io.h>
#include<stdio.h>
#include<winsock2.h>
#define MY_PORT 8989
#define MAXBUF 256
int main(int argc , char *argv[])
{
WSADATA wsa;
SOCKET sockfd , clientfd;
struct sockaddr_in self;
char buffer[MAXBUF];
printf("\nInitialising Winsock...");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("Failed. Error Code : %d",WSAGetLastError());
return 1;
}
printf("Initialised.\n");
/*---create streaming socket---*/
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
{
perror("Socket");
exit(errno);
}
printf("Socket created.\n");
/*---initialize address/port structure---*/
/* bzero(&self, sizeof(self));*/
self.sin_family = AF_INET;
self.sin_port = htons(MY_PORT); // Host to Network Short (16-bit)
self.sin_addr.s_addr = INADDR_ANY;
/*---assign a port number to the socket---*/
if ( bind(sockfd, (struct sockaddr*)&self, sizeof(self)) != 0 )
{
perror("socket--bind");
exit(errno);
}
puts("Bind done");
/*---make it a "listening socket"---*/
if ( listen(sockfd, 20) != 0 )
{
perror("socket--listen");
exit(errno);
}
puts("Waiting for incoming connections...");
/*---forever... ---*/
while (1)
{ struct sockaddr_in client_addr;
int addrlen=sizeof(client_addr);
/*---accept a connection (creating a data pipe)---*/
clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &addrlen);
send(clientfd, buffer, recv(clientfd, buffer, MAXBUF, 0), 0);
/*---close connection---*/
close(clientfd);
}
/*---clean up (should never get here!)---*/
close(sockfd);
WSACleanup();
return 0;
}
0 comment threads