Professional Documents
Culture Documents
Unit 2 and 3
Unit 2 and 3
#include"unp.h"
Int main(intargc, char**argv)
{intlistenfd, connfd;
pid_tchildpid;
socklen_tclilen;
structsockaddr_in cliaddr, servaddr;
listenfd = Socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));
Listen(listenfd, LISTENQ);
for( ; ; ) {
clilen = sizeof(cliaddr);
connfd = Accept(listenfd, (SA *) &cliaddr, &clilen);
if( (childpid = Fork()) == 0) { /* child process */
Close(listenfd); /* close listening socket */
str_echo(connfd); /* process the request */
exit(0);
}Close(connfd); /* parent closes connected socket
TCP Echo Server:str_echoFunction
#include"unp.h"
Void str_echo(intsockfd)
{ ssize_tn;
charbuf[MAXLINE]; again:
while( (n = read(sockfd, buf, MAXLINE)) > 0)
Writen(sockfd, buf, n);
if(n < 0&& errno == EINTR)
gotoagain; elseif(n < 0)
err_sys("str_echo: read error");
UNIT 2
TCP Echo Client :str_cliFunction
#include"unp.h"
void
str_cli(FILE *fp, intsockfd)
{
charsendline[MAXLINE], recvline[MAXLINE];
while(Fgets(sendline, MAXLINE, fp) != NULL)
{
Writen(sockfd, sendline, strlen(sendline));
if(Readline(sockfd, recvline, MAXLINE) == 0)
err_quit("str_cli: server terminated prematurely");
Fputs(recvline, stdout);
}
}
UNIT 2 1. **`getsockname`**: This function is used to retrieve the local
address and port number of a socket. It is typically called after a socket has
been bound to an address using the `bind` function. The `getsockname`
function takes the socket file descriptor as an argument and fills a `struct
sockaddr` structure with the local address information.
Example:
```c
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(addr);
getsockname(sockfd, (struct sockaddr *)&addr, &addr_len);
```
2. **`getpeername`**: This function is used to retrieve the address and port
number of the peer socket to which a connection-oriented socket is
connected. It is typically called on a connected socket (e.g., after a call to
`connect` for TCP sockets). Like `getsockname`, `getpeername` takes the
socket file descriptor as an argument and fills a `struct sockaddr` structure
with the peer's address information.
Example:
```c
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(addr);
getpeername(sockfd, (struct sockaddr *)&addr, &addr_len);
The `getsockname` function is used to retrieve the local IP address and port
number assigned to a socket. It is useful after a successful `connect` in a TCP
client without a `bind`, after calling `bind` with a port number of 0, and in a
TCP server that binds the wildcard IP address to obtain the local IP address
assigned to a connection
The `getpeername` function is used to obtain the address and port number
of the peer socket in a connected socket. It is useful for identifying the client
in a server process that has been `exec`ed by the process calling `accept`.
getsockopt and setsockopt Functions:
•sockfd must refer to an open socket descriptor.
•level specifies the code in the system that interprets the option: the general
socket code or some protocol-specific code (e.g., IPv4, IPv6, TCP, or SCTP).
•optval is a pointer to a variable from which the new value of the option is
fetched by getsockopt, or into which the current value of the option is stored
by setsockopt.
•The size of this variable is specified by the final argument, as a value for
setsockopt and as a value-result for getsockopt.
#include ‹sys/socket.h>
int getsockopt(int sockfd, int level, int
optname, void *optval, socklen_t *optlen);
int setsockopt(int sockfd, int level, int
optname, const void *optval socklen_t
optlen);
Both return: 0 if OK, 1 on
There are two basic types of options:
•binary options that enable or disable a certain feature (flags), and
•options that fetch and return specific values that we can either set or
examine (values).
•The column labelled "Flag" specifies if the option is a flag option.
•When calling getsockopt for these flag options, *optval is an integer.
•The value returned in *optval is zero if the option is disabled, or nonzero if
the option is enabled. Similarly, setsockopt requires a nonzero *optval to
turn the option on, and a zero value to turn the option off.
•If the "Flag" column does not contain a "•," then the option is used to pass
a value of the specified datatype between the user process and the system.
SOCKETR FUNCTION FOR UDP CLIENT AND SERVER UNIT 3
There are fundamental differences between applications written using TCP
versus those that use UDP.
•It is because differences in UDP and TCP protocols.
•UDP is a connectionless, unreliable, datagram protocol.
•TCP is connection-oriented, reliable byte stream.
•Applications built using UDP are: DNS, NFS, and SNMP
sendto() and recvfrom()
Example:
```c
struct servent *service_info;
service_info = getservbyport(htons(80), "tcp")
Domain Name Systems(DNS).
•The DNS is used primarily to map between hostnames and IP addresses.
•A hostname can be either a simple name, such as solarisor freebsdor
google.
•A fully qualified domain name (FQDN) such as solaris.unpbook.com.
•An FQDN is also called an absolute name and must end with a DOT, but
users often omit the ending period.
•The trailing DOT tells the resolver that this name is fully qualified and it
doesn't need to search its list of possible domains.
•In network servers, the parent calls accept and then calls fork.
•The connected socket is then shared between the parent and child.
•Normally, the child then reads and writes the connected socket and the
parent closes the connected socket.
•There are two typical uses of fork:
1.A process makes a copy of itself so that one copy can handle one operation
while the other copy does another task.
2.A process wants to execute another program. Since the only way to create
a new process is by calling fork, the process first calls fork to make a copy of
itself, and then one of the copies (typically the child process) calls exec
(described next) to replace itself with the new program.
Here are some common socket functions used in network programming,
along with their syntax and a brief explanation: