Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- #include <fcntl.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- int main(int argc, char **argv){
- int n;
- int flags, err, opts;
- char *host_ip = "127.0.0.1";
- char *remote_ip = "127.0.0.1";
- int remote_port;
- int host_sock, remote_sock;
- char msg[1000];
- struct sockaddr_in host_add;
- struct sockaddr_in remote_add;
- unsigned int host_len = sizeof(host_add);
- if(argc>1){
- perror("Zu viele Argumente!!!\n");
- return 0;
- }
- host_sock = socket(AF_INET, SOCK_DGRAM, 0);
- flags = fcntl(host_sock, F_GETFL,0); //SOCKET- NONBLOCKING I|O
- err = fcntl(host_sock, F_SETFL, flags | O_NONBLOCK);
- opts = fcntl(STDIN_FILENO, F_GETFL, 0); //STDIN- NONBLOCKING I|O
- fcntl(STDIN_FILENO, F_SETFL, opts | O_NONBLOCK);
- opts = fcntl(STDOUT_FILENO, F_GETFL, 0); //STDOUT- NONBLOCKING I|O
- fcntl(STDOUT_FILENO, F_SETFL, opts | O_NONBLOCK);
- host_add.sin_family = AF_INET;
- host_add.sin_port = htons(0);
- host_add.sin_addr.s_addr = inet_addr(host_ip);
- bind(host_sock, (struct sockaddr *)&host_add, sizeof(host_add));
- getsockname(host_sock, (struct sockaddr*)&host_add, &host_len);
- printf("\n");
- printf("Local port is: %d\n", (int) ntohs(host_add.sin_port));
- printf("Port des Kommunikationspartner: ");
- scanf("%i", &remote_port);
- remote_sock = socket(AF_INET, SOCK_DGRAM, 0);
- remote_add.sin_family = AF_INET;
- remote_add.sin_port = htons(remote_port);
- remote_add.sin_addr.s_addr = inet_addr(remote_ip);
- while(1){
- if((n=read(STDIN_FILENO, msg, sizeof(msg)))<0){
- if(errno!=EWOULDBLOCK){
- printf("FEHLER (NICHT EWOULDBLOCK)");
- }
- }
- else {
- write(remote_sock, msg, sizeof(msg));
- bzero(msg, sizeof(msg));
- }
- if((n=read(remote_sock, msg, sizeof(msg)))<0){
- if(errno!=EWOULDBLOCK){
- printf("FEHLER (NICHT EWOULDBLOCK)");
- }
- }
- else {
- write(STDOUT_FILENO, msg, sizeof(msg));
- fprintf(stdout,msg,sizeof(msg));
- }
- bzero(msg, sizeof(msg));
- }
- close(remote_sock);
- close(host_sock);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement