Visualizzazione dei risultati da 1 a 3 su 3
  1. #1

    [C/Socket] Comunicare Tra Server su Linux e Client su Win ?

    Come faccio a far comunicare 2 programmi in C (con i socket),
    Uno (che e' il server) si trova su un Sistema Linux e il Client si trova su un sistema Windows.

    Qualcuno puo' farmi qualche esempio rapido di comunicazione tra i 2. Magari una cosa del tipo: il client invia un carattere al server e il server lo stampa a video.

    Grazie.

  2. #2
    Il Server (Linux) e' una cosa del Genere
    codice:
    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <string.h>
    #include <sys/socket.h>
    #include <sys/select.h>
    #include <arpa/inet.h>
    
    #define PORT 5091
    #define BUFFER_SIZE 1024
    
    int main() {
    	fd_set fds, rfds;
    	int s, fd, fdc, fdm;
    	struct sockaddr_in myaddr, remoteaddr;
    	char buf[BUFFER_SIZE];
    
    	if ((s = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
    		perror("socket()");
    		exit(-1);
    	};
    
    	myaddr.sin_family = AF_INET;
    	myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    	myaddr.sin_port = htons(PORT);
    	memset(&(myaddr.sin_zero), 0, sizeof(myaddr.sin_zero));
    
    	if (bind(s, (struct sockaddr *) &myaddr, sizeof(myaddr)) == -1) {
    		perror("bind()");
    		exit(-1);
    	}
    
    	if (listen(s, 5) == -1) {
    		perror("listen()");
    		exit(-1);
    	}
    
    	FD_ZERO(&fds);
    	FD_SET(s, &fds);
    	fdm = s;
    
    	while (1) {
    		rfds = fds;
    
    		if (select(fdm + 1, &rfds, NULL, NULL, NULL) == -1) {
    			perror("select()");
    			exit(-1);
    		}
    
    		for (fd = 0; fd <= fdm; ++fd) {
    			if (FD_ISSET(fd, &rfds)) {
    				if (fd == s) {
    					socklen_t addrlen = sizeof(remoteaddr);
    
    					if ((fdc = accept(s, (struct sockaddr *) &remoteaddr, &addrlen)) != -1) {
    						if (fdc > fdm) fdm = fdc;
    						printf("connessione da %s, FD %d\n", inet_ntoa(remoteaddr.sin_addr), fdc);
    						FD_SET(fdc, &fds);
    					} else perror("accept()");
    				} else {
    					int c = recv(fd, buf, sizeof(buf), 0);
    
    					if ((c > 0) && (*buf != EOF)) {
    						for (fdc = 0; fdc <= fdm; ++fdc)
    							if (FD_ISSET(fdc, &fds) && (fdc != fd) && (fdc != s))
    								if (send(fdc, buf, c, 0) < 0) perror("send()");
    					} else {
    						if (c < 0) perror("recv()");
    						printf("scollegamento di %d\n", fd);
    						close(fd);
    						FD_CLR(fd, &fds);
    					}
    				}
    			}
    		}
    	}
    
    	return (0);
    }

  3. #3

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.