i have a chat client server in C, i will give you 2 codes for the client :
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <errno.h>
#include <ifaddrs.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <signal.h>
#include <pthread.h>
#define PORT1 2058
#define PORT2 2059
void* threadReadTerminal();
void* threadSocket(void argv);
void threadGetChatMessage(void *argv);
char username[255]; // Add a global variable for the username
int main(int argc, char *argv[]) { // client
if (argc != 3) {
printf("Number of arguments must be 2 and not %d\\n", argc);
}
printf("Enter your username: ");
scanf("%s", username); // Ask the user for their username
pthread_t th1, th2, th3;
pthread_create(&th1, NULL, threadReadTerminal, NULL);
pthread_create(&th2, NULL, threadSocket, argv);
pthread_create(&th3, NULL, threadGetChatMessage, argv);
pthread_join(th1,NULL);
pthread_join(th2,NULL);
exit(0);
}
void* threadReadTerminal(){
char message[255];
mode_t mode;
int tub;
// Define access rights for the named pipe
mode = 0644; // or S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH;
// Create a named pipe called "fictub" with the specified rights
mkfifo("msgtub", mode);
// Open the named pipe in write-only mode (O_WRONLY)
tub = open("msgtub", O_WRONLY);
while(strncmp(message,"quit",4)!=0){
scanf("%s", message);
write(tub, message, 255);
//printf("\\033[A\\33[2K");
}
pthread_exit(NULL);
}
void* threadSocket(void *argv){
mode_t mode;
int tub;
char** arg = (char**)argv;
char* ipAdd = arg[1];
int port = atoi(arg[2]);
// Define access rights for the named pipe
mode = 0644; // or S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH;
// Create a named pipe called "fictub" with the specified rights
mkfifo("msgtub", mode);
// Open the named pipe in write-only mode (O_WRONLY)
tub = open("msgtub", O_RDONLY);
int sock;
struct sockaddr_in adr_s, adr_c;
char message[255];
while(strncmp(message,"quit",4)!=0){
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // Creation socket
bzero(&adr_s,sizeof(adr_s));
adr_s.sin_family = AF_INET;
adr_s.sin_port = htons(port);
adr_s.sin_addr.s_addr = inet_addr(ipAdd);
connect(sock, (struct sockaddr *) &adr_s, sizeof(adr_s));
read(tub, message, 255);
char full_message[512];
sprintf(full_message, "%s: %s", username, message); // Prepend the username to the message
write(sock, full_message, sizeof(full_message));
}
close(sock);
pthread_exit(NULL);
}
void* threadGetChatMessage(void *argv){
char** arg = (char**)argv;
char* ipAdd = arg[1];
int port = atoi(arg[2]);
int sock, nsock, lg, n;
pid_t pid; char buf[255];
struct sockaddr_in adr_s, adr_c;
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // Creation socket
bzero(&adr_s,sizeof(adr_s));
adr_s.sin_family = AF_INET;
adr_s.sin_port = htons(port);
adr_s.sin_addr.s_addr = inet_addr(ipAdd);
bind (sock, (struct sockaddr *) &adr_s, sizeof(adr_s));
listen(sock, 5);
while (1) {
lg = sizeof(adr_c);
nsock = accept(sock, (struct sockaddr *) &adr_c, &lg);
pid = fork();
if (pid==0) {
close(sock);
while(1){
read(nsock,buf,255);
printf("%s\\n", buf);
printf("\\a");
}
close(nsock);
exit(0);
}
}
pthread_exit(NULL);
}
this is the first code it doesnt work but i want to take a part of this code and put it in the 2nd code i will give you. the part i want is the one concerning the username
here is the second client code where you should put the username code, dont modify anything else :
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include<errno.h>
#include<ifaddrs.h>
#include<stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <signal.h>
#include <pthread.h>
#define PORT1 2058
#define PORT2 2059
void* threadReadTerminal();
void* threadSocket(void argv);
void threadGetChatMessage(void *argv);
char* ipAdd;
int port;
int main(int argc, char *argv[]) { // client
if (argc != 4) {
printf("Number of arguments must be 3 and not %d\n", argc);
}
char** arg = (char**)argv;
ipAdd = arg[1];
port = atoi(arg[2]);
pthread_t th1, th2, th3;
pthread_create(&th1, NULL, threadReadTerminal, NULL);
pthread_create(&th2, NULL, threadSocket, argv);
pthread_create(&th3, NULL, threadGetChatMessage, argv);
pthread_join(th1,NULL);
pthread_join(th2,NULL);
exit(0);
}
void* threadReadTerminal(){
char message[255];
mode_t mode;
int tub;
// Définir les droits d'accès pour le tube nommé
mode = 0644; // ou S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH;
// Créer un tube nommé appelé "fictub" avec les droits spécifiés
mkfifo("msgtub", mode);
// Ouvrir le tube nommé en mode écriture seulement (O_WRONLY)
tub = open("msgtub", O_WRONLY);
printf("Pseudo :"); //Renseigner le pseudo
scanf("%s", message);
write(tub, message, 255);
printf("\033[A\33[2K");
while(strncmp(message,"quit",4)!=0){
scanf("%s", message);
write(tub, message, 255);
printf("\033[A\33[2K");
}
pthread_exit(NULL);
}
void* threadSocket(void argv){
mode_t mode;
int tub;
char* arg = (char**)argv;
char* ipAdd = arg[1];
int port = atoi(arg[2]);
mode = 0644; // ou S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH;
mkfifo("msgtub", mode);
// Ouvrir le tube nommé en mode écriture seulement (O_WRONLY)
tub = open("msgtub", O_RDONLY);
int sock;
struct sockaddr_in adr_s;
char message[255];
while(strncmp(message,"quit",4)!=0){
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bzero(&adr_s,sizeof(adr_s));
adr_s.sin_family = AF_INET;
adr_s.sin_port = htons(port);
adr_s.sin_addr.s_addr = inet_addr(ipAdd);
connect(sock, (struct sockaddr *) &adr_s, sizeof(adr_s));
read(tub, message, 255);
write(sock, message, sizeof(message));
}
close(sock);
pthread_exit(NULL);
}
void* threadGetChatMessage(void *argv){
char** arg = (char**)argv;
char* ipAdd = arg[1];
int port = atoi(arg[3]);
int sock, n;
char buffer[255];
struct sockaddr_in serverAddress;
// Create a socket
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("Error creating socket");
}
// Setup the server address
memset(&serverAddress, 0, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(port);
serverAddress.sin_addr.s_addr = INADDR_ANY;
// Bind the socket to the server address
if (bind(sock, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0) {
perror("Error binding socket");
close(sock);
}
// Listen for incoming connections
if (listen(sock, 5) < 0) {
perror("Error listening on socket");
close(sock);
}
// Accept an incoming connection
int clientSocket;
struct sockaddr_in clientAddress;
socklen_t clientAddressLength = sizeof(clientAddress);
while (1) {
clientSocket = accept(sock, (struct sockaddr *) &clientAddress, &clientAddressLength);
if (clientSocket < 0) {
perror("Error accepting connection");
close(sock);
}
// Receive the message from the server
memset(buffer, 0, sizeof(buffer));
n = read(clientSocket, buffer, sizeof(buffer) - 1);
if (n < 0) {
perror("Error reading from socket");
close(sock);
close(clientSocket);
}
// Print the message from the server
printf("Message from server: %s\n", buffer);
}
close(sock);
close(clientSocket);
pthread_exit(NULL);
}
void signalHandler(int signum, siginfo_t *info, void *context) {
if (signum == SIGINT) {
printf("\nRéception de CTRL+C (SIGINT). Fin du programme.\n");
struct sockaddr_in adr_s;
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
bzero(&adr_s,sizeof(adr_s));
adr_s.sin_family = AF_INET;
adr_s.sin_port = htons(port);
adr_s.sin_addr.s_addr = inet_addr(ipAdd);
connect(sock, (struct sockaddr *) &adr_s, sizeof(adr_s));
write(sock, "quit", 4);
exit(EXIT_SUCCESS);
}
}
void setSignalListener(){
struct sigaction sa;
sa.sa_sigaction = signalHandler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_SIGINFO;
sigaction(SIGALRM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
}
also if you need to modify the server codes here is the code of the first server which doesnt work in general but you can take the username part :
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define PORT 2058
#define CLIENT_PORT 2059
#define CLIENT_LIST_MAX_SIZE 100
typedef struct Client{
char* pseudo;
int socket;
}Client;
typedef struct ClientList{
int lastIndex;
Client storage[CLIENT_LIST_MAX_SIZE];
}ClientList;
Client createClient(char*, int);
void printClient(const Client);
ClientList addClient(ClientList, const Client);
void printClientList(const ClientList);
void sendMessageToClient(const Client, const char*);
void sendMessageToClients(const ClientList, const char*);
int main() {
char buf[255];
const int shmkey = 1337;
const int shmid = shmget(shmkey, sizeof(ClientList), 0644|IPC_CREAT);
if (shmid == -1) {
perror("Shared memory");
return 1;
}
// Attach to the segment to get a pointer to it.
ClientList *list = shmat(shmid, NULL, 0);
list->lastIndex = 0;
struct sockaddr_in adr_s, adr_c;
const int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // Creation socket
bzero( & adr_s, sizeof(adr_s));
adr_s.sin_family = AF_INET;
adr_s.sin_port = htons(PORT);
adr_s.sin_addr.s_addr = htonl(INADDR_ANY);
bind(sock, (struct sockaddr * ) & adr_s, sizeof(adr_s));
listen(sock, 5);
while (1) {
int lg = sizeof(adr_c);
const int nsock = accept(sock, (struct sockaddr * ) & adr_c, & lg);
char pseudo[255];
read(nsock, pseudo, 255); // lire le pseudo du client
const Client newClient = createClient(pseudo, nsock); // utiliser le pseudo pour créer le client
*list = addClient(*list, newClient);
printf("NEW CLIENT!! \n");
printClientList(*list);
printf("Message reçu : %s \n", buf);
sendMessageToClients(*list, buf);
if(strncmp(buf, "quit", 4)== 0){
close(sock);
close(nsock);
}
exit(0);
}
}
Client createClient(char* pseudo, int socket){
const Client client = {pseudo, socket};
return client;
}
void printClient(const Client c){
printf("client pseudo: %s, socket: %d\n", c.pseudo, c.socket);
}
void printClientList(const ClientList list){
for(int i = 0; i < list.lastIndex; i++){
printf("Client %d: \n", i);
printClient(list.storage[i]);
}
}
ClientList addClient(ClientList list, const Client client){
list.storage[list.lastIndex++] = client;
return list;
}
void sendMessageToClient(const Client client, const char* message){
write(client.socket, message, 255);
}
void sendMessageToClients(const ClientList list, const char* message){
for(int i=0; i < list.lastIndex; i++){
char full_message[255];
sprintf(full_message, "%s:%s", list.storage[i].pseudo, message); // concaténer le pseudo et le message
sendMessageToClient(list.storage[i], full_message);
}
}
and here is the second code of the server that works perfectly but where i would like to add the username thing :
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include "logger.h"
#include <semaphore.h>
sem_t* listsemaphore;
#define PORT 2058
#define CLIENT_PORT 2059
#define CLIENT_LIST_MAX_SIZE 10
#define strequals(a,