I wrote a login server with fork in C using txt file as a database. I found a problem when im trying to use my client more than one time, that sometimes its bugs, and doesnt print anything in the console.
Here is the server code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <arpa/inet.h>
FILE* fp;
int main() {
int server_socket;
socklen_t addr_size;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
char buffor[1024], info[21], pass[21], decision[10];
pid_t childpid;
fp = fopen("baza.txt", "a+");
server_socket = socket(AF_INET, SOCK_STREAM,0);
if(server_socket < 0){
printf("Błąd tworzenia socketu.\n");
exit(EXIT_FAILURE);
}
printf("Utworzono socket\n");
memset(&server_address,'\0',sizeof(server_socket));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr = inet_addr("127.0.0.1");
if ((bind(server_socket, (struct sockaddr*) &server_address, sizeof(server_address)))<0){
printf("Błąd przy przybijaniu gniazda");
exit(EXIT_FAILURE);
}
listen(server_socket, 20);
while(1){
rewind(fp);
int client_socket = accept(server_socket, (struct sockaddr*)&client_address, &addr_size);
printf("Połączenie od IP: %s i portu: %d\n",inet_ntoa(client_address.sin_addr),ntohs(client_address.sin_port));
if ((childpid = fork()) == 0){
bzero(&decision,sizeof(decision));
bzero(&buffor,sizeof(buffor));
bzero(&pass,sizeof(pass));
recv(client_socket,&decision,sizeof(decision),0);
FILE *local_fp = fdopen(fileno(fp),"a+");
int foundlog = 0;
int foundrej = 0;
char line[100];
if(strcmp(decision,"log")==0){
rewind(local_fp);
recv(client_socket,&buffor,sizeof(buffor),0);
strcat(buffor,"login");
while(fscanf(local_fp,"%100s",info)==1){
if(strcmp(info, buffor)==0){
send(client_socket,"Znaleziono login",strlen("znaleziono login"),0);
foundlog = 1;
}
}
if (foundlog==0){
send(client_socket,"Nie ma takiego loginu", strlen("Nie ma takiego loginu"),0);
exit(EXIT_FAILURE);
}
rewind(local_fp);
if (foundlog==1){
recv(client_socket,&pass,sizeof(pass),0);
strcat(buffor,"\t");
strcat(buffor,pass);
while(fgets(line,100,local_fp)!=NULL){
if(strstr(line,buffor)!=NULL){
send(client_socket,"Zalogowano",strlen("Zalogowano"),0);
foundlog=2;
}
}
}
if (foundlog==1){
send(client_socket,"Hasło nie pasuje do nazwy użytkownika",strlen("Hasło nie pasuje do nazwy użytkownika"),0);
exit(EXIT_FAILURE);
}
}
if(strcmp(decision,"rej")==0){
recv(client_socket,&buffor,sizeof(buffor),0);
strcat(buffor,"login");
while(fscanf(local_fp,"%100s",info)==1){
if(strcmp(info, buffor)==0){
send(client_socket,"Taki login już istnieje",strlen("Taki login już istnieje"),0);
exit(EXIT_FAILURE);
}
}
send(client_socket,"Podany login jest wolny",strlen("Podany login jest wolny"),0);
recv(client_socket,&pass,sizeof(pass),0);
strcat(buffor,"\t");
strcat(buffor,pass);
rewind(local_fp);
fprintf(local_fp,"%s\n",buffor);
send(client_socket,"Zarejestrowano nowego użytkownika",strlen("Zarejestrowano nowego użytkownika"),0);
}
fclose(local_fp);
close(client_socket);
}
close(client_socket);
}
fclose(fp);
return 0;
}
And client
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <arpa/inet.h>
int main(){
int client_socket;
char login[20], info[20], ans[1024], pass[20];
client_socket = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_address;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr = INADDR_ANY;
system("clear");
int status = connect(client_socket, (struct sockaddr *) &server_address, sizeof(server_address));
if (status == -1){
printf("Nie udało się połączyć do serwera\n");
exit(EXIT_FAILURE);
}
bzero(&login,sizeof(login));
bzero(&ans,sizeof(ans));
bzero(&info,sizeof(info));
printf("--------Witaj na serwerze--------\n");
printf("Wybierz operację\n");
printf("1. Rejestracja\n");
printf("2. Logowanie\n");
scanf("%s",info);
if((strcmp(info, "logowanie")) == 0 || (strcmp(info,"2")) == 0){
send(client_socket,"log",strlen("log"),0);
system("clear");
printf("Wybrano zalogowanie\n");
printf("Login: ");
scanf("%s",login);
if((send(client_socket,&login,sizeof(login),0))<0){
printf("Błąd przy wysyłaniu\n");
}
if((recv(client_socket,&ans,sizeof(ans),0))<0){
printf("Błąd przy odbieraniu\n");
}
printf("%s\n",ans);
bzero(&ans,sizeof(ans));
printf("Podaj hasło: ");
scanf("%s",pass);
send(client_socket,&pass,sizeof(pass),0);
recv(client_socket,&ans,sizeof(ans),0);
printf("Odpowiedź z serwera: %s\n",ans);
}
if((strcmp(info, "rejestracja")) == 0 || (strcmp(info,"1")) == 0){
send(client_socket,"rej",strlen("rej"),0);
system("clear");
printf("Wybrano tworzenie nowego użytkownika\n");
printf("Podaj swój login:");
scanf("%s",login);
if((send(client_socket,&login,sizeof(login),0))<0){
printf("Błąd przy wysyłaniu\n");
}
if((recv(client_socket,&ans,sizeof(ans),0))<0){
printf("Błąd przy odbieraniu\n");
}
printf("%s\n",ans);
printf("Podaj swoje hasło:");
scanf("%s",pass);
send(client_socket,&pass,sizeof(pass),0);
recv(client_socket,&ans,sizeof(ans),0);
printf("Odpowiedź z serwera: %s\n",ans);
}
return 0;
}
And output of the terminal
the database looks like this
macieklogin 123
kubalogin 123
kacperlogin 1234
I have tried rewriting the client and server but it didnt help at all
Related
I made a simple Process-based parallel socket program.
My client code reaches the connect part and throws an Invalid argument error, and my server doesn't ouput anything. just cursor...
I split the terminal in two to run the code.
I run the code with:
gcc -o p-server p-server.c -Wall
./p-server
gcc -o p-client p-client.c -Wall
The output is
[C] Connecting...
[C] Can't connect to a Server: Invalid argument
p-server.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
//#include <sys/wait.h>
#define BUFFSIZE 4096
#define SERVERPORT 7799
int main(void){
int i, j, s_sock, c_sock;
struct sockaddr_in server_addr, client_addr;
socklen_t c_addr_size;
char buf[BUFFSIZE] = {0};
char hello[] = "Hello~ I am Server!\n";
//int option = 1;
//setsockopt(s_sock, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVERPORT);
server_addr.sin_addr.s_addr = inet_addr("10.0.0.131");
s_sock = socket(AF_INET, SOCK_STREAM, 0);
if (bind(s_sock, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1) {
perror("[S] Can't bind a socket");
exit(1);
}
if(listen(s_sock, 5)) {
perror("[S] Can't listen");
exit(1);
}
c_addr_size = sizeof(client_addr);
for ( i=0; i<3; i++) {
if ((c_sock = accept(s_sock, (struct sockaddr *) &client_addr, sizeof(client_addr))) == -1 ){
perror("[S] Can't accept a connection");
exit(1);
}
printf("[S] Connected: client IP addr=%s port=%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
//fork
switch(fork()){
case 0:
close(s_sock);
//1. say hello to client
if(send(c_sock, hello, sizeof(hello)+1, 0) == -1) {
perror("[S] Can't send message");
exit(1);
}
printf("[S] I said Hello to Client!\n");
//2. recv msg from client
if(recv(c_sock, buf, BUFFSIZE, 0) == -1) {
perror("[S] Can't receive message");
exit(1);
}
printf("[S] Client says: %s\n", buf);
exit(0);
}
close(c_sock);
}
/*
for(j=0; j<3; j++){
wait(&status);
printf("Patren waits %d\n"), wstatus;
}*/
}
p-client.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFFSIZE 4096
#define SERVERPORT 7799
int main(void){
int c_sock;
struct sockaddr_in server_addr;
socklen_t c_addr_size;
char buf[BUFFSIZE] = {0};
char hello[] = "Hi~I am Client!\n";
if((c_sock = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVERPORT);
server_addr.sin_addr.s_addr = inet_addr("10.0.0.131");
printf("[C] Connecting...\n");
if (connect(c_sock, (struct sockaddr *) &server_addr, sizeof(server_addr) == -1)) {
perror("[C] Can't connect to a Server");
exit(1);
}
printf("[C] connected!\n");
//1. recv msg from server (maybe it's "hello")
if (recv(c_sock, buf, BUFFSIZE, 0) == -1) {
perror("[C] Can't receive message");
exit(1);
}
printf("[C] Server says: %s\n", buf);
//2. say hi to server
if(send(c_sock, hello, sizeof(hello)+1, 0) == -1) {
perror("[C] Can't send message");
exit(1);
}
printf("[C] I said Hi to Server!!\n");
printf("[C] I am going to sleep...\n");
sleep(10);
close(c_sock);
return 0;
}
I'm very new to socket and TCP, I'm trying to send an array of Int to the server, do some sorting and calculating, then send back the result to the client and repeat.
I tried a few different ways, I either got the result after I close the client or got into a infinite loop.
What is the proper way to keep reading from the client until the client hit EOF?
Here is my server code.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char const *argv[]) {
struct sockaddr_in server, client;
int sock, csock, readSize, addressSize;
char buf[256];
bzero(&server, sizeof(server));
server.sin_family = PF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(5999);
sock = socket(PF_INET, SOCK_STREAM, 0);
bind(sock, (struct sockaddr*)&server, sizeof(server));
listen(sock, 5);
addressSize = sizeof(client);
csock = accept(sock, (struct sockaddr *)&client, &addressSize);
int values[5];
while (read(csock, values, sizeof(values))) {
// Some sorting and calculating here
for (int i = 0; i < 5; i++) {
printf("%d ", values[i]);
}
}
close(sock);
return 0;
}
And here is my client code.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char const *argv[]) {
struct sockaddr_in server;
char buf[256];
int sock;
bzero(&server, sizeof(server));
server.sin_family = PF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(5999);
sock = socket(PF_INET, SOCK_STREAM, 0);
connect(sock, (struct sockaddr *)&server, sizeof(server));
while (1) {
int values[5] = {0};
for (int i = 0; i < 5; i++)
scanf("%d", &values[i]);
write(sock, values, sizeof(values));
}
return 0;
}
Thanks for your help!
On Linux, I observed that if client is terminated with Ctrl-C, then server exits when read() returns 0 to signify EOF. If client is given a Ctrl-D, the stream's error state is set and this and all future scanf calls fail without setting values. This means values retain their zero initialization, which is sent to server in each iteration of the infinite loop.
Per #user207421, recv() which I guess how read() is implemented may return on error on windows to signify and errors. In this case, server would loop with the original code.
In either case, I added error checking for most of calsl (you should also add it for inet_addr()), and the server will terminate if read() returns either -1 or 0:
server:
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <unistd.h>
int main(int argc, char const *argv[]) {
struct sockaddr_in server, client;
int sock, csock;
socklen_t addressSize;
bzero(&server, sizeof(server));
server.sin_family = PF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(5999);
sock = socket(PF_INET, SOCK_STREAM, 0);
if(sock == -1) {
printf("socket: %s\n", strerror(errno));
return 1;
}
if(bind(sock, (struct sockaddr*)&server, sizeof(server)) == -1) {
printf("bind: %s\n", strerror(errno));
return 1;
}
if(listen(sock, 5) == -1) {
printf("listen: %s\n", strerror(errno));
return 1;
}
addressSize = sizeof(client);
csock = accept(sock, (struct sockaddr *)&client, &addressSize);
if(csock == -1) {
printf("listen: %s\n", strerror(errno));
return 1;
}
int values[5];
ssize_t n;
while ((n = read(csock, values, sizeof(values)))) {
printf("read %zd\n", n);
if(n <= 0) break;
for (int i = 0; i < n / sizeof(*values); i++) {
printf("%d ", values[i]);
}
printf("\n");
}
close(sock);
return 0;
}
and client:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
int main(int argc, char const *argv[]) {
struct sockaddr_in server;
char buf[256];
int sock;
bzero(&server, sizeof(server));
server.sin_family = PF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(5999);
sock = socket(PF_INET, SOCK_STREAM, 0);
if(sock == -1) {
printf("socket: %s\n", strerror(errno));
return 1;
}
if(connect(sock, (struct sockaddr *)&server, sizeof(server)) == -1) {
printf("connect: %s\n", strerror(errno));
return 1;
}
while (1) {
int values[5] = {0};
for (int i = 0; i < 5; i++) {
int r = scanf("%d", &values[i]);
if(r == EOF) {
return 0;
}
}
ssize_t n = write(sock, values, sizeof(values));
if(n == -1) {
printf("write: %s\n", strerror(errno));
return 1;
}
printf("wrote %zd\n", n);
}
return 0;
}
and here is the output from the server:
$ ./server
read 20 bytes
1 2 3 4 5
and the client (note; client doesn't send partial data):
$ ./client
1
2
3
4
5
wrote 20
1
I am trying to broadcast a UDP message from the server to client. I would like for the server to send the broadcast to the client and then for the client to acknowledge the broadcast. They both compile with no errors but the server will not send the broadcast. The server says it successfully binds. Any tips would be helpful please.
Client.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#define PORT 8081
int main (int argc, char* argv[]){
int clientsocket;
int reuse = 1;
int reuseaddr;
int bind_sock;
int rec_broad;
int send_ack;
char dgram[512];
char client_message[2000];
struct sockaddr_in serv_address;
struct sockaddr_in group;
if (argc != 3) {
printf("Command line args should be multicast group and port\n");
printf("(e.g. for SSDP, `listener 239.255.255.250 1900`)\n");
return 1;
}
clientsocket = socket(AF_INET, SOCK_DGRAM, 0);
if(clientsocket < 0){
printf("\n\tSocket not created.\n");
exit(1);
}
else printf("\n\tSocket created successfully.\n");
reuseaddr = setsockopt(clientsocket, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse));
if(reuseaddr < 0){
printf("\n\tSetting REUSEADDR error.\n");
exit(1);
}
else printf("\n\tREUSEADDR Successful.\n");
serv_address.sin_family = AF_INET;
serv_address.sin_port = htons(PORT);
serv_address.sin_addr.s_addr = inet_addr(argv[1]);
/*bind_sock = bind(clientsocket, (struct sockaddr*) &serv_address, sizeof(serv_address));
if(bind_sock < 0){
printf("\n\tBind unsuccessful.\n");
exit(1);
}
else printf("\n\tBind Successful.\n");*/
strcpy(client_message, "Acknowledged.\n");
for(;;){
printf("\nListening........\n");
rec_broad = recvfrom(clientsocket, dgram, sizeof(dgram), 0, (struct sockaddr*) &serv_address, sizeof(serv_address));
if(rec_broad < 0){
printf("\n\tBroadcast not received.\n");
exit(1);
}
else printf("\n\tBroadcast received successfully.\n");
send_ack = sendto(clientsocket, client_message, sizeof(client_message), 0, (struct sockaddr*)&serv_address, sizeof(serv_address));
if (send_ack < 0){
printf("\n\tAck not sent.\n");
}
else printf("\n\tAcknowledge sent successfully.\n");
}
return 0;
}
Server.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 8081
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
int main (int argc, char *argv[]){
int serv_socket;
struct sockaddr_in broadcast_addr;
struct sockaddr_in client_addr;
int b_addr_len;
int ret;
int bind_sock;
int yes = 1;
char buffer[2000];
int send_broad;
int z;
//Create socket
serv_socket = socket(AF_INET, SOCK_DGRAM, 0);
if(serv_socket < 0){
printf("\n\tProblem1.\n");
exit(1);
}
else printf("\n\tSocket made successful.\n");
//Setsockopt
ret = setsockopt(serv_socket, SOL_SOCKET, SO_BROADCAST, (char*)&yes, sizeof(yes));
if(ret < 0){
printf("\n\tSetsockopt error.\n");
return -1;
}
else printf("\n\tSetsockopt successful.\n");
b_addr_len = sizeof(broadcast_addr);
//Broadcast Address
memset((void*)&broadcast_addr, 0, b_addr_len);
broadcast_addr.sin_family = AF_INET;
broadcast_addr.sin_addr.s_addr = inet_addr(argv[1]);
broadcast_addr.sin_port = htons(atoi(argv[2]));
//Bind socket with client
bind_sock = bind(serv_socket, (struct sockaddr*) &client_addr, b_addr_len);
if (ret < 0){
printf("\n\tBind unsuccessful.\n");
exit(1);
}
else printf("\n\tBind successful.\n");
memset(buffer, '\0', 2000);
strcpy(buffer, "This is the broadcast!\n");
//Send broadcast
send_broad = sendto(serv_socket, buffer, sizeof(buffer), 0, (struct sockaddr*)&broadcast_addr, b_addr_len);
if(send_broad < 0){
printf("\n\tBroadcast not sent.\n");
exit(1);
}
else printf("\n\tBroadcast sent OK.\n");
return 0;
}
this is program for file transfer server and client
Both server and client code I ran normally. However, when I used the diff command to compare the original file and the transmitted file, only the words 'binary files test.txt and receivefile.txt differ' were output. I know you can compare binary files using cmp, but I have to use diff. How do I change the code so I can compare the two with the diff command?
server code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFFSIZE 4096
#define SERVERPORT 7799
int main(void){
int s_sock, c_sock;
struct sockaddr_in server_addr, client_addr;
socklen_t c_addr_size;
char buf[BUFFSIZE] = {0};
char filename[BUFFSIZE] = {0};
int read_len;
int newfile;
int writefile;
int fileread_len;
s_sock = socket(AF_INET, SOCK_STREAM, 0);
bzero(&server_addr, sizeof(server_addr));
int option = 1;
setsockopt(s_sock, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
// already in use error
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVERPORT);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(s_sock, (struct sockaddr *) &server_addr, sizeof(server_addr)) == -1){
perror("bind error");
exit(1);
}
listen(s_sock,1);
c_addr_size = sizeof(struct sockaddr);
c_sock = accept(s_sock, (struct sockaddr *) &client_addr, &c_addr_size);
if(c_sock == -1){
perror("accept error");
exit(1);
}
read_len = read(c_sock, buf, BUFFSIZE);
if(read_len > 0){
strcpy(filename,buf);
}else{
close(c_sock);
printf("file len error");
}
newfile = open(filename, O_RDONLY);
if(!newfile){
perror("there is no file for open");
exit(1);
}
while((fileread_len=read(newfile, buf, BUFFSIZE)) != 0){
writefile = write(c_sock, buf, BUFFSIZE);
}
close(c_sock);
close(newfile);
close(s_sock);
return 0;
}
client code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUFFSIZE 4096
#define SERVERPORT 7799
int main(int argc, char* argv[]){
if(argc != 4){
printf("<Usage : ./hw11c IP PORT FILENAME >\n");
}
int c_sock;
struct sockaddr_in server_addr, client_addr;
socklen_t c_addr_size;
char buf[BUFFSIZE] = {0};
char filename[BUFFSIZE] = {0};
int receivefile;
int filenamelen;
int recv_len;
c_sock = socket(AF_INET, SOCK_STREAM, 0);
bzero(&server_addr, sizeof(server_addr));
int option = 1;
setsockopt(c_sock, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));
// already in use
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(atoi(argv[2]));
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
strcpy(filename,argv[3]);
filenamelen = strlen(filename);
if(connect(c_sock,(struct sockaddr *)&server_addr, sizeof(server_addr)) == -1){
perror("connect error");
exit(1);
}
send(c_sock, filename, filenamelen, 0);
receivefile = open("receivefile.txt", O_CREAT | O_EXCL | O_WRONLY ,0700);
// receivefile = open(filename, O_CREAT | O_EXCL | O_RDWR);
if(!receivefile){
perror("there is no receive file");
exit(1);
}
while((recv_len = recv(c_sock, buf, BUFFSIZE, 0)) != 0)
{
write(receivefile, buf, recv_len);
}
close(receivefile);
close(c_sock);
return 0;
}
I am writing a simple client/server chat program in c. I am not understanding why one program works and the other doesn't. The programs given for client and server which are working are below. When I replace bzero(&(server.sin_zero),8) with bzero((char*)server,sizeof(server)) in both codes, it throws an error that "transport endpoint is not connected". They have implemneted using the second method and it works at this site.
Client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
struct sockaddr_in server;
int s1;
char message[500];
server.sin_port = htons(5000);
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
bzero(&(server.sin_zero),8);
s1 = socket(AF_INET,SOCK_STREAM,0);
if(s1 == -1) {
perror("socket not created\n");
exit(1);
}
if(connect(s1,(struct sockaddr *)&server,sizeof(server)) == -1) {
perror("not able to connect\n");
exit(1);
}
int n = read(s1,message,500);
if(n < 0) {
perror("message not recieved\n");
exit(1);
}
printf("%s\n",message);
close(s1);
return 0;
}
Here is the program for the server.
Server.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{
struct sockaddr_in server,client;
int s1,s2,len;
char message[500];
server.sin_port = htons(5000);
server.sin_addr.s_addr = INADDR_ANY;
server.sin_family = AF_INET;
bzero(&(server.sin_zero),8);
s1 = socket(AF_INET,SOCK_STREAM,0);
if(s1 == -1) {
perror("socket not created\n");
exit(1);
}
if(bind(s1,(struct sockaddr *)&server,sizeof(struct sockaddr)) == -1) {
perror("socket not binded\n");
exit(1);
}
if(listen(s1,5) == -1) {
perror("unable to listen");
exit(1);
}
len = sizeof(struct sockaddr_in);
s2 = accept(s1,(struct sockaddr *)&client,&len);
printf("connected");
if(s2 == -1) {
perror("unable to accept connection");
exit(1);
}
strcpy(message,"you are connected");
message[strlen(message)] = '\0';
int n = write(s2,message,strlen(message));
if(n < 0) {
perror("message not sent\n");
exit(1);
}
close(s1);
close(s2);
return 0;
}
bzero(&(server.sin_zero),8)
only zeroes out the sin_zero array.
bzero((char*)server,sizeof(server))
on the other hand, zeroes out the whole struct, thus resetting the values you set before (like sin_port).
Finally, first zero out the struct, then initialize it (just like they did it on the site you referred to; pay attention to the details :-)).