套接字网络编程,该怎么解决

套接字网络编程
哪位大侠能帮我解释下面几个问题

一:为什么这两段程序都不终止呢?原因分别是什么
1.

#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char **argv, char **envp) {
struct protoent *pe = getprotobyname("tcp");

int s = socket(AF_INET, SOCK_STREAM, pe -> p_proto);
struct sockaddr_in indirizzo;
indirizzo.sin_family = AF_INET;
indirizzo.sin_addr.s_addr = INADDR_ANY;
indirizzo.sin_port = htons(0);

 bind(s, (struct sockaddr *)&indirizzo, sizeof(indirizzo));

struct sockaddr_in ind_locale;
unsigned int len = sizeof(ind_locale);
int r = getsockname(s, (struct sockaddr *) &ind_locale, &len);


if (r < 0) {
perror("bind");
return -1;
}

printf("Porta allocata: %d\n", ind_locale.sin_port);

if (listen(s, 128) < 0) {
perror("listen");
return -1;
}

struct sockaddr_in chiamante;
len = sizeof(chiamante);
int data_socket = accept(s, (struct sockaddr *) &chiamante, &len);
if (data_socket < 0) {
perror("accept");
return -1;
}



return 0;
}


2

#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <unistd.h>

int main(int argc, char **argv, char **envp) {
struct protoent *pe = getprotobyname("tcp");

int s = socket(AF_INET, SOCK_STREAM, pe -> p_proto);
struct sockaddr_in indirizzo;
indirizzo.sin_family = AF_INET;
indirizzo.sin_addr.s_addr = INADDR_ANY;
indirizzo.sin_port = htons(0);

 bind(s, (struct sockaddr *)&indirizzo, sizeof(indirizzo));

struct sockaddr_in ind_locale;
unsigned int len = sizeof(ind_locale);
int r = getsockname(s, (struct sockaddr *) &ind_locale, &len);


if (r < 0) {
perror("bind");
return -1;
}

printf("Porta allocata: %d\n", ind_locale.sin_port);

if (listen(s, 128) < 0) {
perror("listen");
return -1;
}

struct sockaddr_in chiamante;
len = sizeof(chiamante);
int data_socket = accept(s, (struct sockaddr *) &chiamante, &len);
if (data_socket < 0) {
perror("accept");
return -1;
}

int dim_buffer = 1024;
char buffer[dim_buffer];

r = recv(data_socket, buffer, dim_buffer, 0);
if (r < 0) {
perror("recv");
return -1;
}

buffer[r - 2] = '\0';

printf("Ricevuta stringa '%s', usando %d  byte\n", buffer, r);