Sockets
Sockets
Sockets
Socket connection
AF_UNIX
UNIX internal(via the file system)
AF_INET
UNIX network sockets(TCP/IP networking)
1. Creating a Socket
#include <sys/types.h>
#include <sys/socket.h>
3. Socket address
struct sockaddr_un{
sa_family_t sun_family;
char sun_path[];
};
In Internet domain, the address is speci-
fied with this structure:
#include <sys/netinet/in.h>
struct sockaddr_in{
short int sin_family;
unsigned short int sin_port;
struct in_addr sin_addr;
};
The IP address structure is defined as,
#include <sys/netinet/in.h>
struct in_addr{
unsigned long int s_addr;
};
5. Requesting a connections
#include <sys/socket.h>
int close(sd);
Applications
1. A local client
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
int sockfd; //socket descriptor
int len; //len of address
char ch = ’A’;
/* client create a socket*/
sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
int server_sockfd;
int client_sockfd;
int server_len;
int client_len;
/* accept a client*/
client_len= sizeof(client_address);
client_sockfd= accept(server_sockfd,
(struct sockaddr *)
&client_address,
&client_len);
socket on network
1. Network client
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
int sockfd; //socket descriptor
int len; //len of address
struct sockaddr_in address;
int result; //result from connection
char ch = ’A’;
2. Network server
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
int server_sockfd;
int client_sockfd;
int server_len;
int client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
/* accept a client*/
client_len= sizeof(client_address);
client_sockfd= accept(server_sockfd,
(struct sockaddr *)
&client_address,
&client_len);
Multiple Clients
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
int server_sockfd;
int client_sockfd;
int server_len;
int client_len;
pid_t pid;
/* accept a client*/
client_len= sizeof(client_address);
client_sockfd= accept(server_sockfd,
(struct sockaddr *)
&client_address,
&client_len);
1. Structure hostent
#include <netdb.h>
2. Structure servent
#include <netdb.h>
#include <arpa/inet.h>
Function prototype
#indude <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <netdb.h>
#include <stdio.h>
/* call gethostbyname */
hostinfo = gethostbyname(host);
if(!hostinfo){
printf("can’t get info for host %s\n", host);
exit(1);
}
while(*names){
printf("%s", *names);
names++;
}
printf("\n");