Skip to content
Snippets Groups Projects
Commit 0d50ec80 authored by Peter Gerwinski's avatar Peter Gerwinski
Browse files

Tafelbild: Partitionierung, ext2, Beispiel-Programme: Netzwerkprogrammierung

parent 1a934f47
No related branches found
No related tags found
No related merge requests found
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define TARGET_HOST "localhost"
#define PORT 1234
#define MESSAGE "Hello, world!\n"
void error (char *msg)
{
fprintf (stderr, "%s\n", msg);
exit (1);
}
int main (void)
{
int s;
struct sockaddr_in name;
if ((s = socket (PF_INET, SOCK_STREAM, 0)) < 0)
error ("cannot create socket");
memset (&name, 0, sizeof (name));
name.sin_family = AF_INET;
name.sin_port = htons (PORT);
name.sin_addr.s_addr = htonl (INADDR_ANY);
struct hostent *ho = gethostbyname (TARGET_HOST);
if (!ho)
{
close (s);
error ("name server lookup error");
}
if (ho->h_length > (int) sizeof (name.sin_addr))
ho->h_length = sizeof (name.sin_addr);
memcpy (&name.sin_addr, ho->h_addr, ho->h_length);
if (connect (s, (struct sockaddr *) &name, sizeof (name)) < 0)
{
close (s);
error ("cannot connect to socket");
}
send (s, MESSAGE, strlen (MESSAGE), 0);
shutdown (s, SHUT_RDWR);
close (s);
return 0;
}
20170707/photo-20170707-150500.jpg

138 KiB

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define PORT 1234
#define MESSAGE "Hello, world!\n"
void error (char *msg)
{
fprintf (stderr, "%s\n", msg);
exit (1);
}
int main (void)
{
int s;
struct sockaddr_in name;
if ((s = socket (PF_INET, SOCK_STREAM, 0)) < 0)
error ("cannot create socket");
memset (&name, 0, sizeof (name));
name.sin_family = AF_INET;
name.sin_port = htons (PORT);
name.sin_addr.s_addr = htonl (INADDR_ANY);
int on = 1;
setsockopt (s, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof (on));
if (bind (s, (struct sockaddr *) &name, sizeof (name)) < 0)
{
close (s);
error ("cannot bind socket");
}
if (listen (s, 16) < 0)
{
close (s);
error ("cannot listen on socket");
}
struct sockaddr_in clientname;
size_t size = sizeof (clientname);
s = accept (s, (struct sockaddr *) &clientname, &size);
if (s < 0)
error ("cannot accept connection");
char *host_address = inet_ntoa (clientname.sin_addr);
char *host_name;
struct hostent *hp = gethostbyaddr ((void *) &clientname.sin_addr, sizeof (clientname.sin_addr), clientname.sin_family);
if (hp)
host_name = hp->h_name;
else
host_name = inet_ntoa (clientname.sin_addr);
int remote_port = ntohs (clientname.sin_port);
printf ("connection from %s [%s], port %d\n",
host_name, host_address, remote_port);
send (s, MESSAGE, strlen (MESSAGE), 0);
shutdown (s, SHUT_RDWR);
close (s);
return 0;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment