├── Python ├── Half Duplex TCP │ ├── client.py │ └── server.py ├── Day Time │ ├── client.py.py │ └── server.py.py ├── Chat App │ ├── client.py │ └── server.py ├── UDP Echo │ ├── client.py │ └── socket.py └── Full Duplex TCP │ ├── client.py │ └── server.py ├── C ├── Day Time │ ├── client.c │ └── server.c ├── UDP Echo │ ├── client.c │ └── server.c ├── Remote UDP │ ├── client.c │ └── server.c ├── Full Duplex TCP │ ├── client.c │ └── server.c ├── Chat Application │ ├── client.c │ └── server.c └── Half Duplex TCP │ ├── server.c │ └── client.c └── README.md /Python/Half Duplex TCP/client.py: -------------------------------------------------------------------------------- 1 | # Client Side Script 2 | # Supports Python v3.* 3 | 4 | from socket import * 5 | server_name = 'localhost' 6 | server_port = 5000 7 | client_socket = socket(AF_INET, SOCK_STREAM) 8 | client_socket.connect((server_name,server_port)) 9 | 10 | while True: 11 | sentence = input(">> ") 12 | client_socket.send(sentence.encode()) 13 | message = client_socket.recv(2048) 14 | print (">> ", message.decode()) 15 | if(sentence == 'q'): 16 | client_socket.close() 17 | -------------------------------------------------------------------------------- /Python/Day Time/client.py.py: -------------------------------------------------------------------------------- 1 | # client.py 2 | import socket 3 | 4 | # create a socket object 5 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 6 | 7 | # get local machine name 8 | host = socket.gethostname() 9 | 10 | port = 9999 11 | 12 | # connection to hostname on the port. 13 | s.connect((host, port)) 14 | 15 | # Receive no more than 1024 bytes 16 | tm = s.recv(1024) 17 | 18 | s.close() 19 | 20 | print("The time got from the server is %s" % tm.decode('ascii')) -------------------------------------------------------------------------------- /Python/Half Duplex TCP/server.py: -------------------------------------------------------------------------------- 1 | # Server Side Script 2 | # Supports Python v3.* 3 | 4 | from socket import * 5 | server_port = 5000 6 | server_socket = socket(AF_INET,SOCK_STREAM) 7 | server_socket.bind(('',server_port)) 8 | server_socket.listen(1) 9 | print ("Welcome: The server is now ready to receive") 10 | connection_socket, address = server_socket.accept() 11 | while True: 12 | sentence = connection_socket.recv(2048).decode() 13 | print('>> ',sentence) 14 | message = input(">> ") 15 | connection_socket.send(message.encode()) 16 | if(message == 'q'): 17 | connectionSocket.close() 18 | -------------------------------------------------------------------------------- /Python/Chat App/client.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | 4 | def client_program(): 5 | host = socket.gethostname() # as both code is running on same pc 6 | port = 5000 # socket server port number 7 | 8 | client_socket = socket.socket() # instantiate 9 | client_socket.connect((host, port)) # connect to the server 10 | 11 | message = input(" -> ") # take input 12 | 13 | while message.lower().strip() != 'bye': 14 | client_socket.send(message.encode()) # send message 15 | data = client_socket.recv(1024).decode() # receive response 16 | 17 | print('Received from server: ' + data) # show in terminal 18 | 19 | message = input(" -> ") # again take input 20 | 21 | client_socket.close() # close the connection 22 | 23 | 24 | if __name__ == '__main__': 25 | client_program() -------------------------------------------------------------------------------- /Python/Day Time/server.py.py: -------------------------------------------------------------------------------- 1 | # server.py 2 | import socket 3 | import time 4 | 5 | # create a socket object 6 | serversocket = socket.socket( 7 | socket.AF_INET, socket.SOCK_STREAM) 8 | 9 | # get local machine name 10 | host = socket.gethostname() 11 | 12 | port = 9999 13 | 14 | # bind to the port 15 | serversocket.bind((host, port)) 16 | 17 | # queue up to 5 requests 18 | serversocket.listen(5) 19 | 20 | while True: 21 | # establish a connection 22 | clientsocket,addr = serversocket.accept() 23 | 24 | print("Got a connection from %s" % str(addr)) 25 | currentTime = time.ctime(time.time()) + "\r\n" 26 | clientsocket.send(currentTime.encode('ascii')) 27 | clientsocket.close() -------------------------------------------------------------------------------- /C/Day Time/client.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | int main(int argc, char **argv){ 10 | if(argc != 2){ 11 | printf("Usage: %s \n", argv[0]); 12 | exit(0); 13 | } 14 | 15 | int port = atoi(argv[1]); 16 | printf("Port: %d\n", port); 17 | 18 | int sockfd = socket(AF_INET, SOCK_STREAM, 0); 19 | char response[30]; 20 | struct sockaddr_in serverAddress; 21 | serverAddress.sin_family = AF_INET; 22 | serverAddress.sin_addr.s_addr = INADDR_ANY; 23 | serverAddress.sin_port = htons(port); 24 | 25 | connect(sockfd, (struct sockaddr*)&serverAddress, sizeof(serverAddress)); 26 | printf("[+]Connected to the server\n"); 27 | 28 | recv(sockfd, response, 29, 0); 29 | printf("Time from server: %s", response); 30 | 31 | return 0; 32 | 33 | } -------------------------------------------------------------------------------- /C/UDP Echo/client.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #define MAXLINE 1024 10 | int main(int argc,char* argv[]) 11 | { 12 | int sockfd; 13 | int n; 14 | socklen_t len; 15 | char sendline[1024],recvline[1024]; 16 | 17 | 18 | struct sockaddr_in servaddr; 19 | strcpy(sendline,""); 20 | printf("\n Enter your message : "); 21 | scanf("%s",sendline); 22 | 23 | sockfd=socket(AF_INET,SOCK_DGRAM,0); 24 | bzero(&servaddr,sizeof(servaddr)); 25 | servaddr.sin_family=AF_INET; 26 | servaddr.sin_addr.s_addr=inet_addr("127.0.0.1"); 27 | servaddr.sin_port=htons(1234); 28 | 29 | connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr)); 30 | len=sizeof(servaddr); 31 | 32 | sendto(sockfd,sendline,MAXLINE,0,(struct sockaddr*)&servaddr,len); 33 | n=recvfrom(sockfd,recvline,MAXLINE,0,NULL,NULL); 34 | recvline[n]=0; 35 | 36 | printf("\n Server Echoed : %s\n\n",recvline); 37 | return 0; 38 | } -------------------------------------------------------------------------------- /C/UDP Echo/server.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #define MAXLINE 1024 10 | int main(int argc,char **argv) 11 | { 12 | int sockfd; 13 | int n; 14 | socklen_t len; 15 | char msg[1024]; 16 | 17 | struct sockaddr_in servaddr,cliaddr; 18 | sockfd=socket(AF_INET,SOCK_DGRAM,0); 19 | bzero(&servaddr,sizeof(servaddr)); 20 | servaddr.sin_family=AF_INET; 21 | servaddr.sin_addr.s_addr=INADDR_ANY; 22 | 23 | servaddr.sin_port=htons(1234); 24 | 25 | bind(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr)); 26 | printf("\n\n Listening..."); 27 | for(;;) 28 | { 29 | printf("\n "); 30 | len=sizeof(cliaddr); 31 | n=recvfrom(sockfd,msg,MAXLINE,0,(struct sockaddr*)&cliaddr,&len); 32 | printf("\n Client's Message : %s\n",msg); 33 | if(n<6) 34 | perror("send error"); 35 | sendto(sockfd,msg,n,0,(struct sockaddr*)&cliaddr,len); 36 | 37 | } 38 | return 0; 39 | } -------------------------------------------------------------------------------- /Python/Chat App/server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | 4 | def server_program(): 5 | # get the hostname 6 | host = socket.gethostname() 7 | port = 5000 # initiate port no above 1024 8 | 9 | server_socket = socket.socket() # get instance 10 | # look closely. The bind() function takes tuple as argument 11 | server_socket.bind((host, port)) # bind host address and port together 12 | 13 | # configure how many client the server can listen simultaneously 14 | server_socket.listen(2) 15 | conn, address = server_socket.accept() # accept new connection 16 | print("Connection from: " + str(address)) 17 | while True: 18 | # receive data stream. it won't accept data packet greater than 1024 bytes 19 | data = conn.recv(1024).decode() 20 | if not data: 21 | # if data is not received break 22 | break 23 | print("from connected user: " + str(data)) 24 | data = input(' -> ') 25 | conn.send(data.encode()) # send data to the client 26 | 27 | conn.close() # close the connection 28 | 29 | 30 | if __name__ == '__main__': 31 | server_program() -------------------------------------------------------------------------------- /C/Day Time/server.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #define BACKLOG 10 10 | 11 | int main(int argc, char **argv){ 12 | if(argc != 2){ 13 | printf("Usage: %s \n", argv[0]); 14 | exit(0); 15 | } 16 | 17 | int port = atoi(argv[1]); 18 | printf("Port: %d\n", port); 19 | 20 | int n_client = 0; 21 | int sockfd = socket(AF_INET, SOCK_STREAM, 0); 22 | struct sockaddr_in serverAddress; 23 | serverAddress.sin_family = AF_INET; 24 | serverAddress.sin_addr.s_addr = INADDR_ANY; 25 | serverAddress.sin_port = htons(port); 26 | 27 | bind(sockfd, (struct sockaddr*)&serverAddress, sizeof(serverAddress)); 28 | printf("[+]Bind\n"); 29 | 30 | listen(sockfd, BACKLOG); 31 | printf("[+]Listening for the client\n"); 32 | 33 | int i = 1; 34 | while(i){ 35 | int client_socket = accept(sockfd, NULL, NULL); 36 | n_client++; 37 | time_t currentTime; 38 | time(¤tTime); 39 | printf("Client %d requested for time at %s", n_client, ctime(¤tTime)); 40 | send(client_socket, ctime(¤tTime), 30, 0); 41 | } 42 | 43 | return 0; 44 | 45 | } -------------------------------------------------------------------------------- /C/Remote UDP/client.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #define MAX 1000 10 | 11 | int main() 12 | { 13 | int serverDescriptor = socket(AF_INET, SOCK_DGRAM, 0); 14 | char buffer[MAX], message[MAX]; 15 | struct sockaddr_in cliaddr, serverAddress; 16 | socklen_t serverLength = sizeof(serverAddress); 17 | 18 | bzero(&serverAddress, sizeof(serverAddress)); 19 | serverAddress.sin_family = AF_INET; 20 | serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1"); 21 | serverAddress.sin_port = htons(9976); 22 | 23 | bind(serverDescriptor, (struct sockaddr *)&serverAddress, sizeof(serverAddress)); 24 | 25 | while (1) 26 | { 27 | printf("\nENTER A COMMAND FOR EXECUTION ... "); 28 | fgets(buffer, sizeof(buffer), stdin); 29 | sendto(serverDescriptor, buffer, sizeof(buffer), 0, (struct sockaddr *)&serverAddress, serverLength); 30 | printf("\nData Sent !"); 31 | recvfrom(serverDescriptor, message, sizeof(message), 0, (struct sockaddr *)&serverAddress, &serverLength); 32 | printf("UDP SERVER : %s", message); 33 | } 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Socket-programming 2 | Simple server and client using C and python socket programming 3 | 4 | ## Table of Contents 5 | 6 | | S.No. | Program Topic | C | Python | 7 | |-------|---------------|---|--------| 8 | | 1 | Chat Application | [link](https://github.com/MainakRepositor/Socket-programming/tree/master/C/Chat%20Application) | [link](https://github.com/MainakRepositor/Socket-programming/tree/master/Python/Chat%20App) | 9 | | 2 | UDP Echo | [link](https://github.com/MainakRepositor/Socket-programming/tree/master/C/Day%20Time) | [link](https://github.com/MainakRepositor/Socket-programming/tree/master/Python/UDP%20Echo) | 10 | | 3 | Day Time | [link](https://github.com/MainakRepositor/Socket-programming/tree/master/C/Day%20Time) | [link](https://github.com/MainakRepositor/Socket-programming/tree/master/Python/Day%20Time) | 11 | | 4 | Half Duplex TCP | [link](https://github.com/MainakRepositor/Socket-programming/tree/master/C/Half%20Duplex%20TCP) | [link](https://github.com/MainakRepositor/Socket-programming/tree/master/Python/Half%20Duplex%20TCP) | 12 | | 5 | Full Duplex TCP | [link](https://github.com/MainakRepositor/Socket-programming/tree/master/C/Full%20Duplex%20TCP) | [link](https://github.com/MainakRepositor/Socket-programming/tree/master/Python/Full%20Duplex%20TCP) | 13 | 14 | -------------------------------------------------------------------------------- /C/Remote UDP/server.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #define MAX 1000 12 | int main() 13 | { 14 | 15 | int serverDescriptor = socket(AF_INET, SOCK_DGRAM, 0); 16 | int size; 17 | char buffer[MAX], message[] = "Command Successfully executed !"; 18 | struct sockaddr_in clientAddress, serverAddress; 19 | 20 | socklen_t clientLength = sizeof(clientAddress); 21 | 22 | bzero(&serverAddress, sizeof(serverAddress)); 23 | serverAddress.sin_family = AF_INET; 24 | serverAddress.sin_addr.s_addr = htonl(INADDR_ANY); 25 | serverAddress.sin_port = htons(9976); 26 | 27 | bind(serverDescriptor, (struct sockaddr *)&serverAddress, sizeof(serverAddress)); 28 | while (1) 29 | { 30 | bzero(buffer, sizeof(buffer)); 31 | recvfrom(serverDescriptor, buffer, sizeof(buffer), 0, (struct sockaddr *)&clientAddress, &clientLength); 32 | system(buffer); 33 | printf("Command Executed ... %s ", buffer); 34 | sendto(serverDescriptor, message, sizeof(message), 0, (struct sockaddr *)&clientAddress, clientLength); 35 | } 36 | close(serverDescriptor); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Python/UDP Echo/client.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | import argparse 4 | 5 | host = 'localhost' 6 | data_payload = 2048 7 | 8 | def echo_client(port): 9 | """ A simple echo client """ 10 | # Create a UDP socket 11 | sock = socket.socket(socket.AF_INET, 12 | socket.SOCK_DGRAM) 13 | 14 | server_address = (host, port) 15 | print ("Connecting to %s port %s" % server_address) 16 | message = 'This is the message. It will be 17 | repeated.' 18 | 19 | try: 20 | 21 | # Send data 22 | message = "Test message. This will be 23 | echoed" 24 | print ("Sending %s" % message) 25 | sent = sock.sendto(message.encode 26 | ('utf-8'), server_address) 27 | 28 | # Receive response 29 | data, server = sock.recvfrom(data_payload) 30 | print ("received %s" % data) 31 | 32 | finally: 33 | print ("Closing connection to the server") 34 | sock.close() 35 | 36 | if __name__ == '__main__': 37 | parser = argparse.ArgumentParser 38 | (description='Socket Server Example') 39 | parser.add_argument('--port', action="store", dest="port", type=int, required=True) 40 | given_args = parser.parse_args() 41 | port = given_args.port 42 | echo_client(port) 43 | -------------------------------------------------------------------------------- /Python/UDP Echo/socket.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import sys 3 | import argparse 4 | 5 | host = 'localhost' 6 | data_payload = 2048 7 | 8 | def echo_server(port): 9 | """ A simple echo server """ 10 | # Create a UDP socket 11 | sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 12 | 13 | # Bind the socket to the port 14 | server_address = (host, port) 15 | print ("Starting up echo server 16 | on %s port %s" % server_address) 17 | 18 | sock.bind(server_address) 19 | 20 | while True: 21 | print ("Waiting to receive message 22 | from client") 23 | data, address = sock. 24 | recvfrom(data_payload) 25 | 26 | print ("received %s bytes 27 | from %s" % (len(data), address)) 28 | print ("Data: %s" %data) 29 | 30 | if data: 31 | sent = sock.sendto(data, address) 32 | print ("sent %s bytes back 33 | to %s" % (sent, address)) 34 | 35 | 36 | if __name__ == '__main__': 37 | parser = argparse.ArgumentParser 38 | (description='Socket Server Example') 39 | parser.add_argument('--port', action="store", dest="port", type=int, required=True) 40 | given_args = parser.parse_args() 41 | port = given_args.port 42 | echo_server(port) 43 | -------------------------------------------------------------------------------- /C/Full Duplex TCP/client.c: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | //headers for socket and related functions 5 | 6 | 7 | //for including structures which will store information needed 8 | 9 | 10 | //for gethostbyname 11 | 12 | 13 | 14 | int main() 15 | { 16 | int socketDescriptor; 17 | 18 | struct sockaddr_in serverAddress; 19 | char sendBuffer[1000],recvBuffer[1000]; 20 | 21 | pid_t cpid; 22 | 23 | bzero(&serverAddress,sizeof(serverAddress)); 24 | 25 | serverAddress.sin_family=AF_INET; 26 | serverAddress.sin_addr.s_addr=inet_addr("127.0.0.1"); 27 | serverAddress.sin_port=htons(5500); 28 | 29 | /*Creating a socket, assigning IP address and port number for that socket*/ 30 | socketDescriptor=socket(AF_INET,SOCK_STREAM,0); 31 | 32 | /*Connect establishes connection with the server using server IP address*/ 33 | connect(socketDescriptor,(struct sockaddr*)&serverAddress,sizeof(serverAddress)); 34 | 35 | /*Fork is used to create a new process*/ 36 | cpid=fork(); 37 | if(cpid==0) 38 | { 39 | while(1) 40 | { 41 | bzero(&sendBuffer,sizeof(sendBuffer)); 42 | printf("\nType a message here ... "); 43 | /*This function is used to read from server*/ 44 | fgets(sendBuffer,10000,stdin); 45 | /*Send the message to server*/ 46 | send(socketDescriptor,sendBuffer,strlen(sendBuffer)+1,0); 47 | printf("\nMessage sent !\n"); 48 | } 49 | } 50 | else 51 | { 52 | while(1) 53 | { 54 | bzero(&recvBuffer,sizeof(recvBuffer)); 55 | /*Receive the message from server*/ 56 | recv(socketDescriptor,recvBuffer,sizeof(recvBuffer),0); 57 | printf("\nSERVER : %s\n",recvBuffer); 58 | } 59 | } 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /C/Chat Application/client.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | 11 | void error(const char *msg) 12 | { 13 | perror(msg); 14 | exit(0); 15 | } 16 | 17 | int main(int argc, char *argv[]) 18 | { 19 | int sockfd, portno, n; 20 | struct sockaddr_in serv_addr; 21 | struct hostent *server; 22 | 23 | char buffer[255]; 24 | if (argc < 3) 25 | { 26 | fprintf(stderr,"usage %s hostname port\n", argv[0]); 27 | exit(0); 28 | } 29 | portno = atoi(argv[2]); 30 | sockfd = socket(AF_INET, SOCK_STREAM, 0); 31 | if (sockfd < 0) 32 | error("ERROR opening socket"); 33 | server = gethostbyname(argv[1]); 34 | if (server == NULL) { 35 | fprintf(stderr,"ERROR, no such host\n"); 36 | exit(0); 37 | } 38 | bzero((char *) &serv_addr, sizeof(serv_addr)); 39 | serv_addr.sin_family = AF_INET; 40 | bcopy((char *)server->h_addr, 41 | (char *)&serv_addr.sin_addr.s_addr, 42 | server->h_length); 43 | serv_addr.sin_port = htons(portno); 44 | if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) 45 | error("ERROR connecting"); 46 | 47 | while(1) 48 | { 49 | bzero(buffer,255); 50 | fgets(buffer,255,stdin); 51 | n = write(sockfd, buffer, strlen(buffer)); 52 | if (n < 0) 53 | { 54 | error("Error in writing!"); 55 | } 56 | 57 | bzero(buffer,255); 58 | 59 | n = read(sockfd, buffer, 255); 60 | if (n < 0) 61 | { 62 | error("Error in reading!"); 63 | } 64 | 65 | printf("Server : %s",buffer); 66 | 67 | int i = strncmp("Bye",buffer,3); 68 | if(i==0) 69 | break; 70 | } 71 | 72 | close(sockfd); 73 | return 0; 74 | } -------------------------------------------------------------------------------- /C/Half Duplex TCP/server.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | #include "stdlib.h" 3 | #include "string.h" 4 | //headers for socket and related functions 5 | #include 6 | #include 7 | //for including structures which will store information needed 8 | #include 9 | #include 10 | //for gethostbyname 11 | #include "netdb.h" 12 | #include "arpa/inet.h" 13 | #define MAX 1000 14 | #define BACKLOG 5 // how many pending connections queue will hold 15 | int main() 16 | { 17 | char serverMessage[MAX]; 18 | char clientMessage[MAX]; 19 | //create the server socket 20 | int socketDescriptor = socket(AF_INET, SOCK_STREAM, 0); 21 | 22 | 23 | struct sockaddr_in serverAddress; 24 | serverAddress.sin_family = AF_INET; 25 | serverAddress.sin_port = htons(9002); 26 | serverAddress.sin_addr.s_addr = INADDR_ANY; 27 | 28 | //calling bind function to oir specified IP and port 29 | bind(socketDescriptor, (struct sockaddr*)&serverAddress, sizeof(serverAddress)); 30 | 31 | listen(socketDescriptor, BACKLOG); 32 | 33 | //starting the accepting 34 | int clientSocketDescriptor = accept(socketDescriptor, NULL, NULL); 35 | 36 | while (1) 37 | { 38 | printf("\ntext message here .. :"); 39 | scanf("%s", serverMessage); 40 | send(clientSocketDescriptor, serverMessage, sizeof(serverMessage) , 0); 41 | //recieve the data from the server 42 | recv(clientSocketDescriptor, &clientMessage, sizeof(clientMessage), 0) ; 43 | //recieved data from the server successfully then printing the data obtained from the server 44 | printf("\nCLIENT: %s", clientMessage); 45 | 46 | } 47 | //close the socket 48 | close(socketDescriptor); 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /C/Chat Application/server.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | void error(const char *msg) 10 | { 11 | perror(msg); 12 | exit(0); 13 | } 14 | 15 | int main(int argc, char *argv[]) 16 | { 17 | if(argc < 2) 18 | { 19 | fprintf(stderr,"Port number is required. Program terminated!\n"); 20 | exit(1); 21 | } 22 | 23 | int sockfd, newsockfd, portnum, m; 24 | char buffer[255]; 25 | struct sockaddr_in serv_addr, cli_addr; 26 | socklen_t clilen; 27 | sockfd = socket(AF_INET, SOCK_STREAM, 0); 28 | if(sockfd < 0) 29 | { 30 | error("Error opening socket"); 31 | } 32 | bzero((char *) &serv_addr, sizeof(serv_addr)); 33 | portnum = atoi(argv[1]); 34 | 35 | serv_addr.sin_family = AF_INET; 36 | serv_addr.sin_addr.s_addr = INADDR_ANY; 37 | serv_addr.sin_port = htons(portnum); 38 | 39 | if(bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr))<0) 40 | { 41 | error("Binding Failed!"); 42 | } 43 | 44 | listen(sockfd, 6); 45 | clilen = sizeof(cli_addr); 46 | newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); 47 | 48 | if(newsockfd < 0) 49 | error("Error on Acceptance!"); 50 | 51 | 52 | while(1) 53 | { 54 | bzero(buffer,255); 55 | m = read(newsockfd, buffer, 255); 56 | if(m<0) 57 | error ("Error on Reading!"); 58 | 59 | printf("Client : %s\n",buffer); 60 | bzero(buffer,255); 61 | fgets(buffer,255,stdin); 62 | m = write(newsockfd, buffer, strlen(buffer)); 63 | 64 | if(m < 0) 65 | error("Error on Writing"); 66 | 67 | int i = strncmp("Bye",buffer,3); 68 | if(i==0) 69 | break; 70 | } 71 | close(newsockfd); 72 | close(sockfd); 73 | 74 | return 0; 75 | } -------------------------------------------------------------------------------- /C/Full Duplex TCP/server.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | int main(int argc,char *argv[]) 11 | { 12 | int clientSocketDescriptor,socketDescriptor; 13 | 14 | struct sockaddr_in serverAddress,clientAddress; 15 | socklen_t clientLength; 16 | 17 | char recvBuffer[1000],sendBuffer[1000]; 18 | pid_t cpid; 19 | bzero(&serverAddress,sizeof(serverAddress)); 20 | /*Socket address structure*/ 21 | serverAddress.sin_family=AF_INET; 22 | serverAddress.sin_addr.s_addr=htonl(INADDR_ANY); 23 | serverAddress.sin_port=htons(5500); 24 | /*TCP socket is created, an Internet socket address structure is filled with 25 | wildcard address & server’s well known port*/ 26 | socketDescriptor=socket(AF_INET,SOCK_STREAM,0); 27 | /*Bind function assigns a local protocol address to the socket*/ 28 | bind(socketDescriptor,(struct sockaddr*)&serverAddress,sizeof(serverAddress)); 29 | /*Listen function specifies the maximum number of connections that kernel should queue 30 | for this socket*/ 31 | listen(socketDescriptor,5); 32 | printf("%s\n","Server is running ..."); 33 | /*The server to return the next completed connection from the front of the 34 | completed connection Queue calls it*/ 35 | clientSocketDescriptor=accept(socketDescriptor,(struct sockaddr*)&clientAddress,&clientLength); 36 | /*Fork system call is used to create a new process*/ 37 | cpid=fork(); 38 | 39 | if(cpid==0) 40 | { 41 | while(1) 42 | { 43 | bzero(&recvBuffer,sizeof(recvBuffer)); 44 | /*Receiving the request from client*/ 45 | recv(clientSocketDescriptor,recvBuffer,sizeof(recvBuffer),0); 46 | printf("\nCLIENT : %s\n",recvBuffer); 47 | } 48 | } 49 | else 50 | { 51 | while(1) 52 | { 53 | 54 | bzero(&sendBuffer,sizeof(sendBuffer)); 55 | printf("\nType a message here ... "); 56 | /*Read the message from client*/ 57 | fgets(sendBuffer,10000,stdin); 58 | /*Sends the message to client*/ 59 | send(clientSocketDescriptor,sendBuffer,strlen(sendBuffer)+1,0); 60 | printf("\nMessage sent !\n"); 61 | } 62 | } 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /C/Half Duplex TCP/client.c: -------------------------------------------------------------------------------- 1 | #include "stdio.h" 2 | #include "stdlib.h" 3 | #include "string.h" 4 | //headers for socket and related functions 5 | #include 6 | #include 7 | //for including structures which will store information needed 8 | #include 9 | #include 10 | //for gethostbyname 11 | #include "netdb.h" 12 | #include "arpa/inet.h" 13 | 14 | //defines 15 | #define h_addr h_addr_list[0] /* for backward compatibility */ 16 | 17 | #define PORT 9002 // port number 18 | #define MAX 1000 //maximum buffer size 19 | 20 | //main function 21 | int main(){ 22 | char serverResponse[MAX]; 23 | char clientResponse[MAX]; 24 | 25 | //creating a socket 26 | int socketDescriptor = socket(AF_INET, SOCK_STREAM, 0); 27 | 28 | //placeholder for the hostname and my ip address 29 | char hostname[MAX], ipaddress[MAX]; 30 | struct hostent *hostIP; //placeholder for the ip address 31 | //if the gethostname returns a name then the program will get the ip address 32 | if(gethostname(hostname,sizeof(hostname))==0){ 33 | hostIP = gethostbyname(hostname);//the netdb.h fucntion gethostbyname 34 | }else{ 35 | printf("ERROR:FCC4539 IP Address Not "); 36 | } 37 | 38 | struct sockaddr_in serverAddress; 39 | serverAddress.sin_family = AF_INET; 40 | serverAddress.sin_port = htons(PORT); 41 | serverAddress.sin_addr.s_addr = INADDR_ANY; 42 | 43 | connect(socketDescriptor, (struct sockaddr *)&serverAddress, sizeof(serverAddress)); 44 | 45 | // getting the address port and remote host 46 | printf("\nLocalhost: %s\n", inet_ntoa(*(struct in_addr*)hostIP->h_addr)); 47 | printf("Local Port: %d\n", PORT); 48 | printf("Remote Host: %s\n", inet_ntoa(serverAddress.sin_addr)); 49 | 50 | while (1) 51 | { //recieve the data from the server 52 | recv(socketDescriptor, serverResponse, sizeof(serverResponse), 0); 53 | //recieved data from the server successfully then printing the data obtained from the server 54 | printf("\nSERVER : %s", serverResponse); 55 | 56 | printf("\ntext message here... :"); 57 | scanf("%s", clientResponse); 58 | send(socketDescriptor, clientResponse, sizeof(clientResponse), 0); 59 | } 60 | 61 | //closing the socket 62 | close(socketDescriptor); 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /Python/Full Duplex TCP/client.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import select 3 | import sys 4 | 5 | 6 | def main(): 7 | """ 8 | main - Runs the Full Duplex Chat Client 9 | """ 10 | 11 | serverHost = 'localhost' 12 | serverPort = 22222 13 | 14 | try: 15 | clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 16 | except socket.error as err: 17 | print "ERROR: Cannot create client side socket:", err 18 | exit(1) 19 | 20 | while True: 21 | try: 22 | clientSocket.connect((serverHost, serverPort)) 23 | except socket.error as err: 24 | print "ERROR: Cannot connect to chat server", err 25 | print "* Exiting... Goodbye! *" 26 | exit(1) 27 | except: 28 | print "ERROR: Something awful happened!" 29 | exit(1) 30 | break 31 | 32 | recvList = [clientSocket, sys.stdin] 33 | 34 | print "* You are now connected to chat server %s as %s *" % (clientSocket.getpeername(), clientSocket.getsockname()) 35 | 36 | try: 37 | while True: 38 | readyRecvList, readySendList, readyErrList = select.select(recvList, [], []) 39 | 40 | for fd in readyRecvList: 41 | if fd == sys.stdin: 42 | message = sys.stdin.readline().rstrip() 43 | clientSocket.sendall("~" + str(message) + "~") 44 | 45 | if (message == "quit()"): 46 | print "* Exiting chat room! *" 47 | clientSocket.close() 48 | exit(0) 49 | break 50 | 51 | elif fd == clientSocket: 52 | clientSocket.settimeout(3) 53 | try: 54 | message = clientSocket.recv(2048) 55 | except socket.timeout as err: 56 | print "ERROR: The recv() function timed out after 3 seconds! Try again." 57 | except: 58 | print "ERROR: Something awful happened!" 59 | else: 60 | if message == "": 61 | break 62 | else: 63 | print "%s\n" % (message) 64 | clientSocket.settimeout(None) 65 | break 66 | 67 | except select.error as err: 68 | for fd in recvList: 69 | try: 70 | tempRecvList, tempSendList, tempErrList = select.select([fd], [], [], 0) 71 | except select.error: 72 | if fd == clientSocket: 73 | fd.close() 74 | exit(1) 75 | else: 76 | if fd in recvList: 77 | recvList.remove(fd) 78 | fd.close() 79 | 80 | except socket.error as err: 81 | print "ERROR: Cannot connect to chat server", err 82 | print "* Exiting... Goodbye! *" 83 | exit(1) 84 | 85 | if fd in recvList: 86 | fd.close() 87 | 88 | except KeyboardInterrupt: 89 | print "\nINFO: KeyboardInterrupt" 90 | print "* Closing all sockets and exiting chat server... Goodbye! *" 91 | clientSocket.close() 92 | exit(0) 93 | 94 | 95 | if __name__ == '__main__': 96 | main() 97 | -------------------------------------------------------------------------------- /Python/Full Duplex TCP/server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import select 3 | 4 | 5 | def runSelect(): 6 | selectUnsuccessful = True 7 | while selectUnsuccessful: 8 | try: 9 | readyRecvList, readySendList, readyErrList = select.select(recvList, sendList, []) 10 | selectUnsuccessful = False 11 | except select.error: 12 | for fd in recvList: 13 | try: 14 | tempRecvList, tempSendList, tempErrList = select.select([fd], [], [], 0) 15 | except select.error: 16 | if fd == serverSocket: 17 | fd.close() 18 | exit(1) 19 | else: 20 | if fd in recvList: 21 | recvList.remove(fd) 22 | 23 | fd.close() 24 | 25 | return readyRecvList, readySendList 26 | 27 | 28 | def handleListeningSocket(): 29 | try: 30 | newConnectionSocket, addr = serverSocket.accept() 31 | except socket.error as err: 32 | print "\nERROR: Something went wrong in the accept() function call:", err 33 | exit(1) 34 | 35 | try: 36 | recvList.append(newConnectionSocket) 37 | sendList.append(newConnectionSocket) 38 | print "INFO: Connecting socket created between %s and %s" % (newConnectionSocket.getsockname(), newConnectionSocket.getpeername()) 39 | print "* Client %s is ready to chat *" % (str(newConnectionSocket.getpeername())) 40 | except (socket.error, socket.gaierror) as err: 41 | print "\nERROR: Something went wrong with the new connection socket:", err 42 | if newConnectionSocket in recvList: 43 | recvList.remove(newConnectionSocket) 44 | sendList.remove(newConnectionSocket) 45 | 46 | newConnectionSocket.close() 47 | 48 | 49 | def handleConnectedSocket(): 50 | try: 51 | 52 | recvIsComplete = False 53 | rcvdStr = "" 54 | 55 | while not recvIsComplete: 56 | rcvdStr = rcvdStr + fd.recv(1024) 57 | 58 | if fd not in sendList: 59 | sendList.append(fd) 60 | 61 | # ~ is the delimiter used to indicate message start and finish 62 | if rcvdStr.strip('~') != "": 63 | if (rcvdStr[0] == "~") and (rcvdStr[-1] == "~"): 64 | recvIsComplete = True 65 | clientMessage = rcvdStr.strip('~') 66 | else: # if empty string, connection has been terminated 67 | if fd in recvList: 68 | recvList.remove(fd) 69 | 70 | if fd in sendList: 71 | sendList.remove(fd) 72 | 73 | del clientMessages[fd] # Delete connection information 74 | fd.close() 75 | 76 | if clientMessage == "quit()": 77 | print "\n* Client %s has left the chat room *\n" % (str(fd.getpeername())) 78 | 79 | if fd in recvList: 80 | recvList.remove(fd) 81 | fd.close() 82 | 83 | if fd in sendList: 84 | sendList.remove(fd) 85 | fd.close() 86 | 87 | else: 88 | print "\n%s: %s" % (fd.getpeername(), clientMessage) 89 | clientMessages[fd] = str(clientMessage) # add message to dictionary, pending transmission 90 | 91 | except socket.error as err: 92 | print "\nERROR: Connection to the client has abruptly ended:", err 93 | if fd in recvList: 94 | recvList.remove(fd) 95 | 96 | if fd in sendList: 97 | sendList.remove(fd) 98 | 99 | fd.close() 100 | print "* I am ready to chat with a new client! *\n" 101 | 102 | 103 | """ 104 | main - Runs the Full Duplex Chat server 105 | """ 106 | 107 | # Global Variables 108 | serverHost = 'localhost' 109 | serverPort = 22222 110 | recvList = [] 111 | sendList = [] 112 | clientMessages = {} 113 | 114 | 115 | try: 116 | 117 | serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 118 | serverSocket.setblocking(0) 119 | serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 120 | serverSocket.bind((serverHost, serverPort)) 121 | serverSocket.listen(3) 122 | 123 | print "INFO: I am listening at %s" % (str(serverSocket.getsockname())) 124 | print "* I am ready to chat with a new client! *\n" 125 | 126 | except (socket.error, socket.gaierror) as err: 127 | print "\nERROR: Something went wrong in creating the listening socket:", err 128 | exit(1) 129 | 130 | recvList = [serverSocket] 131 | 132 | try: 133 | while True: 134 | serverSocket.setblocking(False) 135 | readyForRecv, readyForSend = runSelect() 136 | 137 | for fd in readyForRecv: 138 | if fd == serverSocket: 139 | handleListeningSocket() 140 | else: 141 | handleConnectedSocket() 142 | 143 | for fd in readyForSend: 144 | try: 145 | if fd in clientMessages.keys(): # See if connection information exists 146 | broadcast = str(clientMessages[fd]) # Add message to broadcast variable 147 | 148 | if broadcast: # See if a message is actually there 149 | for client in readyForSend: # Broadcast message to every connected client 150 | if broadcast != "": 151 | print "* Broadcasting message \"%s\" to %s *" % (str(broadcast), client.getpeername()) 152 | client.send(str(fd.getpeername()) + ": " + str(broadcast)) 153 | 154 | clientMessages[fd] = "" # Empty pending messages 155 | except: 156 | # print "\nERROR: Something awful happened while broadcasting messages" 157 | break 158 | 159 | except socket.error as err: 160 | print "\nERROR: Something awful happened with a connected socket:", err 161 | 162 | if fd in recvList: 163 | recvList.remove(fd) 164 | 165 | if fd in sendList: 166 | sendList.remove(fd) 167 | 168 | fd.close() 169 | 170 | except KeyboardInterrupt: 171 | for fd in recvList: 172 | fd.close() 173 | 174 | for fd in sendList: 175 | fd.close() 176 | 177 | print "\nINFO: KeyboardInterrupt" 178 | print "* Closing all sockets and exiting... Goodbye! *" 179 | exit(0) 180 | --------------------------------------------------------------------------------