1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pwd.h>
#include <limits.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>
#define PORT 6667
#define BUFFER_SIZE 512
void *receive_handler(void *sock_ptr) {
int sock = *(int *)sock_ptr;
char buffer[BUFFER_SIZE];
int bytes_received;
while ((bytes_received = recv(sock, buffer, BUFFER_SIZE - 1, 0)) > 0) {
buffer[bytes_received] = '\0';
printf("%s", buffer);
fflush(stdout);
}
return NULL;
}
int main() {
int sock;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE];
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
perror("Socket creation failed");
exit(EXIT_FAILURE);
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(PORT);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); // or your server IP
if (connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("Connection failed");
exit(EXIT_FAILURE);
}
printf("Connected to chat server.\n");
// Build the nickname as ssh-username@hostname
char username[LOGIN_NAME_MAX];
char hostname[HOST_NAME_MAX];
char nickname[100];
struct passwd *pw = getpwuid(getuid());
if (pw) {
strncpy(username, pw->pw_name, sizeof(username));
} else {
strncpy(username, "unknown", sizeof(username));
}
gethostname(hostname, sizeof(hostname));
snprintf(nickname, sizeof(nickname), "%s@%s", username, hostname);
// Send NICK and USER commands
char nick_cmd[150];
snprintf(nick_cmd, sizeof(nick_cmd), "NICK %s\n", nickname);
send(sock, nick_cmd, strlen(nick_cmd), 0);
snprintf(nick_cmd, sizeof(nick_cmd), "USER %s 0 * :%s\n", nickname, nickname);
send(sock, nick_cmd, strlen(nick_cmd), 0);
// Start receiver thread
pthread_t recv_thread;
pthread_create(&recv_thread, NULL, receive_handler, &sock);
// Main input loop
while (fgets(buffer, sizeof(buffer), stdin)) {
send(sock, buffer, strlen(buffer), 0);
}
close(sock);
return 0;
}
|