Code:
int main(int argc, char *argv[]) {
int socket_fd;
struct sockaddr_in server_address;
struct hostent *server;
char *username, buffer[MAXDATASIZE];
if (argc == 3) username = getenv("USER");
else if (argc == 4) username = argv[3];
else error("Error, invalid number of arguments, need a hostname, port, and a user name (optional).\n");
bzero(buffer,MAXDATASIZE);
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
if (socket_fd < 0) error("Error opening socket");
server = gethostbyname(argv[1]);
if (server == NULL) error("Error, no such host\n");
bzero((char *) &server_address, sizeof(server_address));
server_address.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&server_address.sin_addr.s_addr, server->h_length);
server_address.sin_port = htons(PORT);
if (connect(socket_fd,(struct sockaddr *) &server_address,sizeof(server_address)) < 0) error("Error connecting");
send_message(socket_fd, username, str_len(username));
read_message(socket_fd, buffer, 0);
if (strcmp(buffer, "Enter")==0) {
write(1,username,str_len(username)); write(1," successfully connected to ",27);
write(1,argv[1],str_len(argv[1])); write(1,"!\n",2);
send_message(socket_fd, "ok", 2);
read_message(socket_fd, buffer, 1);
}
else {
write(1,"User ",5); write(1,username,str_len(username));
write(1," already connected to ",22); write(1,argv[1],str_len(argv[1])); write(1,"!\n",2);
send_message(socket_fd, "ok", 2);
}
close(socket_fd);
return 0;
}