Advertisement
yacel100

datosLinuxConf.sh

Jun 27th, 2018
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 33.42 KB | None | 0 0
  1. //-------------PRACTICAS DE REDES---------------------------------------
  2. //1: maquina en laboratorio
  3. 1. asorregenerate
  4. 2. nano examen.topol
  5.  
  6.     netprefix inet
  7.     //machine [id] [ifaz][redvirtual]
  8.     machine 1 0 0
  9.     machine 2 0 0 1 1
  10.     machine 3 0 1
  11.     // Esta configuracion de ejemplo tiene dos hosts(1 y 3) conectados via
  12.     // eth0 a dos redes diferentes, que se interconectan mediante un router(2)
  13.  
  14. 3. vtopol examen.topol
  15. //2: maquinas virtuales: user: root
  16.                         //pwd: cursoredes
  17. 1.Hosts:
  18.     $> ip addr add 192.168.0.1/24 dev eth0
  19.     $> ip addr add fd00:0:0:a::1/64 dev eth0
  20.     $> ip link set eth0 up // Esto nos otorga una fe80::net_id
  21.     $> ip route add default via 192.168.0.2
  22.     $> ip -6 route add default via fd00:0:0:0:a::3
  23.      
  24. 2.Router
  25.     //[hosts excepto los default]
  26.     $>sysctl -w net.ipv6.conf.all.forwarding=1
  27.     $>sysctl net.ipv4.ip-forward=1
  28.    
  29. 3.Configuracion dhcp
  30.     1. Hosts
  31.         $> ip addr del 192.168.0.1/24 dev eth0
  32.     2. Router
  33.         1. Añadir seccion subnet '/etc/dhcp/dhcpd.conf'
  34.         subnet 10.0.0.0 netmask 255.255.255.0 {
  35.             range 10.0.0.11 10.0.0.50;
  36.             option routers 10.0.0.3;
  37.             option broadcast-address 10.0.0.255;
  38.         }
  39.         2. $> service isc-dhcp-server start
  40.     [3. Persistente:En host]
  41.     Añadir a fichero: /etc/network/interfaces
  42.     //Con auto se hace al iniciar la maquina
  43.     auto eth0
  44.     iface eth0 inet dhcp
  45.    
  46.     $> ifup eth0 //[ifdown antes para bajar si estaba activa]  
  47.    
  48. 3.Configuracion persistente ipv6
  49.  
  50.     1. Añadir a fichero: /etc/network/interfaces
  51.    
  52.     auto eth0
  53.     [iface eth0 inet dhcp]// Si quieres dhcp, necesitas server configurado
  54.     iface eth0 inet6 static
  55.         pre-up modprobe ipv6 #make sure the ipv6 module is loaded
  56.         address 2607:f0d0:2001:a::10
  57.         netmask 64
  58.         gateway 2607:f0d0:2001:a::1
  59.         //dns-nameservers 2001:DB8:0:76::101 2001:DB8:0:76::102
  60.        
  61.     auto eth0//quitar si lo has hecho ya antes de ipv6
  62.     iface eth0 inet static
  63.         address 192.168.1.42
  64.         netmask 255.255.255.0
  65.         gateway 192.168.1.1
  66.        
  67.    
  68.     2. configurar/desconfigurar
  69.         $> ifdown eth0
  70.         $> ifup eth0
  71.        
  72.          
  73. 3.Anuncio de prefijos ipv6
  74.  
  75.     1. Eliminar configuracion en Hosts
  76.         $> ip addr del fd00:0:0:a::1/64 dev eth0
  77.         $> ip link set eth0 down
  78.     2. En router
  79.         1. Activar (zebra=yes) en /etc/quagga/daemons
  80.         2. Incluir configuracion en /etc/quagga/zebra.conf
  81.         //Ej: /usr/share/doc/quagga/examples/zebra.conf.sample
  82.         interface eth0
  83.             no ipv6 nd suppress-ra
  84.             ipv6 nd prefix fd00:0:0:a::/64
  85.         interface eth1
  86.             no ipv6 nd suppress-ra
  87.             ipv6 nd prefix fd00:0:0:b::/64
  88.         3. Arrancar demonio
  89.             $> service quagga restart
  90.     3. Hosts
  91.         $> ip link set eth0 up
  92. 3.Comandos útiles
  93.  
  94.     $> ping6 -I eth0 fe80::ff:fe00:100//si usamos fe80 necesitamos especificar la ifaz de salida
  95.     $> ping6 fd00:0:0:b::4
  96.     $> ip addr
  97.     $> ip -6 address show eth0
  98.     $> route -e[-n para numeros]
  99.     $> ip route show [dev eth0]
  100.     $> ip route add 10.40.0.0/16 via 10.72.75.254
  101.     $> hping3 -p 23 -s --flood <ip_vict>[--rand-source]
  102.     $> netstat -at //(comprobar estado conexion)
  103.     $> watch netstat -t -o //(ver temporizador)
  104.    
  105. 4.iptables
  106.  
  107.     $> -A append | -I [n(=1 default)] -D n
  108.     $> iptables save|restore [file]
  109.     $> iptables ... -j REJECT --with-icmp-type
  110.    
  111.     $> iptables -P FORWARD DROP //Politica por defecto mas segura
  112.     $> iptables -A FORWARD -p tcp --dport 80,22 -d <ip> -j ACCEPT
  113.     $> iptables -I FORWARD -m --state ESTABLISHED, RELATED -j ACCEPT
  114.     $> iptables -A INPUT -i eth0 -p tcp --tcp-flags ALL SYN -j DROP
  115.                                             //me fijo | tienen que estar de esos   
  116.                                                 //ALL ALL (XMAS SCAN)
  117.                                                 //NULL NULL(NULL SCAN)
  118.     $> iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE
  119.      // nat dinamico
  120.     $> iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 80 -j DNAT --to 192.168.0.1:7777
  121.      // esconder servidor web en otro puerto
  122.      
  123. 5.DNS
  124.  
  125.     1. /etc/bind/named.conf
  126.         //Comprobar sintaxis: > named-checkconf
  127.         1. Comentar "include"
  128.         2. Añadir dos zonas forward y reverse.
  129.         zone "labfdi.es" {
  130.             type master;
  131.             file "/etc/bind/db.labfdi.es";
  132.         }
  133.  
  134.         zone "0.168.192.in-addr.arpa" {
  135.             type master;
  136.             file "/etc/bind/db.0.168.192";
  137.         }
  138.        
  139.     2.Crear archivos de zonas
  140.     //Comprobar sintaxis: $> named-checkconf <zona> <arcivo>
  141.     forward:
  142.             ; db labfdi
  143.             $TTL 28400
  144.  
  145.             ;start of autority
  146.             labfdi.es.  IN SOA ns.labfdi.es. hostmaster@labfdi.es. (
  147.                             2 ;serial
  148.                             172800 ; refresh
  149.                             900 ; update retry
  150.                             1209600 ; expiry
  151.                             3600); TTL
  152.  
  153.             labfdi.es.  IN NS ns.labfdi.es.
  154.  
  155.             www.labfdi.es.  IN A 192.168.0.200
  156.                     IN AAAA fd00::1
  157.             ns.labfdi.es.  IN A 192.168.0.1
  158.             mail.labfdi.es. IN A 192.168.0.250
  159.  
  160.             labfdi.es.      IN MX 10 mail.labfdi.es.
  161.  
  162.             servidor.labfdi.es. IN CNAME mail.labfdi.es.
  163.            
  164.     reverse:
  165.             ; db 0.168.192
  166.             $TTL 604800
  167.  
  168.             ;start of autority
  169.             0.168.192.in-addr.arpa.  IN SOA ns.labfdi.es hostmaster@labfdi.es. (
  170.                             2 ;serial
  171.                             172800 ; refresh
  172.                             900 ; update retry
  173.                             1209600 ; expiry
  174.                             3600); TTL
  175.  
  176.             0.168.192.in-addr.arpa. IN NS ns.labfdi.es.
  177.             1.0.168.192.in-addr.arpa. IN PTR ns.labfdi.es.
  178.             200.0.168.192.in-addr.arpa. IN PTR www.labfdi.es.
  179.             250.0.168.192.in-addr.arpa. IN PTR mail.labfdi.es.
  180.            
  181.     3. Activar demonio en servidor
  182.         $> service bind9 start
  183.         $> service bind9 status
  184.     4. Configurar host cliente para usar el servidor al hacer consultas
  185.         ;;;Archivo '/etc/resolv.conf':
  186.  
  187.         search ns.labfdi.es.
  188.         nameserver 192.168.0.1
  189.     5. Reiniciar demonio del host cliente.
  190.         $> service bind9 restart
  191.        
  192.     COMANDOS DNS
  193.     $> host -t [registro: a mx ns] www.google.com.
  194.     $> host <ip> //devuelve pointer a hostname
  195.     $> host <hostname> //devueltve ip
  196.     $> dig @dnsserver hostname
  197.     $> dig -x ip
  198.     $> dig +trace hostname // consulta paso a paso
  199.     $> host -v <direccion> [servidor DNS]
  200.    
  201.     Ejemplos Recursividad forward:
  202.    
  203.     <host>
  204.         1. $> host -v www.fdi.ucm.es. a.root-servers.net.
  205.         2. $> host -v www.fdi.ucm.es. a.nic.es.
  206.         3. $> host -v www.fdi.ucm.es. sun.rediris.es.
  207.    
  208.     <dig>
  209.         1. $> dig @a.root-servers.net. www.fdi.ucm.es
  210.         2. $> dig @a.nic.es. www.fdi.ucm.es
  211.         3. $> dig @chico.rediris.es. www.fdi.ucm.es
  212.    
  213.  
  214.     ;; ANSWER SECTION:
  215.     www.fdi.ucm.es.     86400   IN  A   147.96.85.71
  216.  
  217.    
  218.     Recursividad reverse:
  219.  
  220.     1. $> host -v 147.96.85.71 a.in-addr-servers.arpa.
  221.     2. $> host -v 147.96.85.71 u.arin.net.
  222.     3. $> host -v 147.96.85.71 chico.rediris.es.
  223.     ;; ANSWER SECTION:
  224.     71.85.96.147.in-addr.arpa. 86400 IN PTR www.fdi.ucm.es.
  225.  
  226.    
  227.    
  228.                
  229. 7. Configuracion RIP. Todos los hosts:
  230.     1. $> cd /etc/quagga
  231.     2. $> nano daemons //zebra=yes && (ripd=yes||ripng=yes)
  232.     // $> cp /usr/share/doc/quagga/examples/ripd.conf.sample ripd.conf||ripng.conf(=ipv6)
  233.     3. $> touch zebra.conf; nano ripd.conf
  234.     router rip[ //|| ripng(=ipv6)]
  235.     version 2 // || sin esta linea ipv6
  236.     network eth0
  237.     network eth1
  238.     network eth2
  239.     network eth3
  240.     4. $> service quagga restart
  241.    
  242.     5.(opcional: conectarnos con telnet para configurar)
  243.         1. ripd.conf ->Borrar todo y poner:
  244.         no router rip
  245.         password redes
  246.         2. service quagga restart
  247.         3. telnet localhost ripd // insertar password
  248.  
  249. //  COMANDOS PARA SACAR DEL MANUAL EJEMPLOS MUY PARECIDOS A LAS SOLUCIONES
  250. //-Eliminar final de archivo y separar parte del cliente/servidor en dos archivos
  251. //-------------------------------------------------------------------------------
  252. //----: man -L en getaddrinfo | tail -n 200 > sockets.c -------------------------
  253. //Ojo:  
  254. //-Ejemplo UDP. Cambiar hints.socktype a SOCK_STREAM para tcp--------------------
  255. //-hints.ai_family = AF_INET6 //evitar que se utilizen siempre ipv4--------------
  256. //-------------------------------------------------------------------------------
  257.  
  258. //-------------------------------------------------------------------------------
  259. //-----------: man -L en pipe | tail -n 60 > pipe.c -----------------------------
  260. //-------------------------------------------------------------------------------
  261.        
  262. //-------------PRACTICAS DE SISTEMAS OPERATIVOS----------------------------------
  263. //-------------------------------------------------------------------------------
  264. //-----------5-INFORMACIÓN DEL SISTEMA DE FICHEROS-------------------------------
  265. #include <stdio.h>
  266. #include <sys/utsname.h>
  267. #include <unistd.h>
  268. #include <errno.h>
  269. int main(){
  270.     printf("-uname-\n");
  271.     struct utsname buf;
  272.     if (uname(&buf) == -1){
  273.         perror("Error uname:");
  274.         printf("Numero del error %i\n", errno);
  275.     }
  276.     printf("Nombre del sistema: %s\n", buf.sysname);
  277.     printf("Nombre del maquina: %s\n", buf.nodename);
  278.     printf("Nombre de la actualizacion: %s\n", buf.release);printf("Nombre del version: %s\n", buf.version);
  279.     printf("Nombre de la arquitectura: %s\n", buf.machine);
  280.  
  281.     printf("-sysconf-\n");
  282.     printf("Longitud maxima de los argumentos: %ld\n", sysconf(_SC_ARG_MAX));
  283.     printf("Numero maximo de hijos: %ld\n",sysconf(_SC_CHILD_MAX));
  284.     printf("Numero maximo de ficheros: %ld\n",sysconf(_SC_OPEN_MAX));
  285.  
  286.     printf("-pathconf-\n");
  287.     printf("Numero maximo de enlaces: %ld\n", pathconf("/",
  288.     _PC_LINK_MAX));
  289.     printf("Tamaño maximo de la ruta: %ld\n", pathconf("/",
  290.     _PC_PATH_MAX));
  291.     printf("Tamaño maximo de un nombre de fichero: %ld\n",
  292.     pathconf("/", _PC_NAME_MAX));
  293. return 0;
  294. }
  295.  
  296. //---------------INFORMACION DE PROCESO---------------------------------
  297. #include <unistd.h>
  298. #include <sys/types.h>
  299. #include <stdio.h>
  300. #include <pwd.h>
  301. int main(){
  302.     struct passwd *p;
  303.     printf("Id real del proceso: %d\n",getuid());
  304.     printf("Id efectivo del proceso: %d\n",geteuid());
  305.     p = getpwuid(getuid());
  306.     printf("Nombre de Login: %s\n", p->pw_name);
  307.     printf("HOME: %s\n", p->pw_dir);
  308.     printf("UID: %d\n", p->pw_uid);
  309.     printf("Shell: %s\n", p->pw_shell);
  310.     printf("Password: %s\n", p->pw_passwd);
  311.     if (setuid(2) == -1){
  312.         perror("Error:");
  313.         return -1;
  314.     }
  315.     //Los permisos efectivos se modifican para un archivo si tiene activado el bit SUID
  316.     //Lo que permite ejecutar el archivo como si tuvieras los permisos del propietario.
  317.     //Este programa funcionaria con
  318.     //>sudo chown root usu
  319.     //>sudo chmod +s usu
  320.     //Puede suponer un problema de seguridad
  321.     printf("Id real del proceso: %d\n",getuid());
  322.     printf("Id efectivo del proceso: %d\n",geteuid());
  323. return 0;
  324. }
  325.  
  326. //--------------INFORMACION DE TIEMPO-----------------------------------
  327. #include <stdio.h>
  328. #include <time.h>
  329. #include <sys/time.h>
  330. int main(){
  331.     time_t theTime = time(NULL);
  332.  
  333.     printf("time(NULL): %d\n", theTime);
  334.     printf("ctime(time): %s", ctime(&theTime));
  335.     int i = 0;
  336.     int a = 1;
  337.     struct timeval tim;
  338.    
  339.     gettimeofday(&tim,NULL);
  340.     double t1=tim.tv_sec+(tim.tv_usec/1000000.0);
  341.     for (i; i < 100000; ++i){
  342.         ++a;
  343.     }
  344.     gettimeofday(&tim, NULL);
  345.     double t2=tim.tv_sec+(tim.tv_usec/1000000.0);
  346.     printf("%.6lf s transcurridos\n", t2-t1);
  347.  
  348.     struct tm *localT;
  349.     localT = localtime(&theTime);
  350.     printf("Estamos en el año %d\n", localT->tm_year+1900);
  351.     char buffer[50];
  352.  
  353.     strftime(buffer, 50, "Hoy es %A,%H:%M", localT);
  354.     printf("%s\n",buffer);
  355.     return 0;
  356. }
  357.  
  358. //----------------------------------------------------------------------
  359. //----------------6-SISTEMA DE FICHEROS---------------------------------
  360. /*stat, open*/
  361. #include <sys/types.h>
  362. #include <sys/stat.h>
  363. #include <unistd.h>
  364. #include <fcntl.h>
  365. /*printf*/
  366. #include <stdio.h>
  367. /*error*/
  368. #include <errno.h>
  369. /*ctime*/
  370. #include <time.h>
  371.  
  372. /*EMULADOR DE STAT*/
  373. int main(){
  374.    
  375.     int fich;
  376.     struct stat buf;
  377.  
  378.     fich = open("./ejercicio5", O_CREAT);
  379.     if(fich == -1)
  380.     {return -EACCES;}
  381.  
  382.     fstat(fich, &buf);
  383.     /*Mostrar el major asociado al dispositivo*/
  384.     printf("Número de major: %d\n", major(buf.st_rdev));
  385.     /*Mostrar el minor asociado al dispositivo*/
  386.     printf("Número de minor: %d\n", minor(buf.st_rdev));
  387.     /*Mostrar el i-nodo del archivo*/
  388.     printf("Número de i-nodo: %ld\n", buf.st_ino);
  389.     /*Mostrar el tipo de archivo(directorio, enlace simbolico o archivo ordinario)*/
  390.     if(S_ISREG(buf.st_mode)){
  391.         printf("Archivo ordinario.\n");
  392.     }
  393.     else if(S_ISDIR(buf.st_mode))
  394.     {
  395.         printf("Directorio.\n");
  396.     }
  397.     else if(S_ISLNK(buf.st_mode))
  398.     {
  399.         printf("Enlace simbólico.\n");
  400.     }
  401.     /*La hora en la que se accedió el fichero por última vez*/
  402.     printf("Hora de último acceso al fichero: %s\n", ctime(&buf.st_atime));
  403.     return 0;
  404. }
  405.  
  406. // enlaces de ficheros
  407. /*link, symlink*/
  408. #include <unistd.h>
  409. /*printf*/
  410. #include <stdio.h>
  411.  
  412. int main(){
  413.  
  414.     link("./ejercicio5","./enlaceDuro.hard");
  415.     printf("Creado enlace duro.\n");
  416.     symlink("./ejercicio5", "./enlaceSym.sym");
  417.     printf("Creado enlace simbólico.\n");
  418.     return 0;
  419.  
  420. }
  421.  
  422. /*dup y dup2*/
  423. #include <unistd.h>
  424. /*open*/
  425. #include <sys/types.h>
  426. #include <sys/stat.h>
  427. #include <fcntl.h>
  428. /*printf*/
  429. #include <stdio.h>
  430.  
  431.  
  432. int main(int argc, char **argv){
  433.     int fd;
  434.     fd=open(argv[1], O_CREAT | O_RDWR, 0640);
  435.     /*Se cambia la salida estándar al fichero abierto */
  436.     dup2(fd,1);
  437.     dup2(fd,2);
  438.    
  439.     close(fd);
  440.     /*EScribimos en el fichero*/
  441.     printf("HOLA MUNDO\n");
  442.     perror("ERROR.");
  443.     return 0;
  444. }
  445.  
  446. #include <unistd.h>
  447. #include <stdio.h>
  448. #include <sys/types.h>
  449. #include <sys/stat.h>
  450. #include <fcntl.h>
  451. #include <errno.h>
  452. #include <string.h>
  453. #include <time.h>
  454. #include <stdlib.h>
  455.  
  456. int main(int argc, char ** argv) {
  457.     if(argc != 2) {
  458.         printf("Usage: ./ej2 <fname>\n");
  459.         return -1;
  460.     }
  461.     int fd;
  462.     fd = open(argv[1], O_CREAT | O_RDWR, 0777);
  463.     if (fd == -1) {
  464.         printf("Error opening file, %i - %s\n", errno, strerror(errno));
  465.         return -1;
  466.     }
  467.     struct flock fl;
  468.    
  469.     fl.l_type = F_WRLCK; /* F_RDLCK, F_WRLCK, F_UNLCK*/
  470.     fl.l_whence = SEEK_SET; /* SEEK_SET(Start), SEEK_CUR(puntero current), SEEK_END*/
  471.     fl.l_start = 0; /* Offset from l_whence*/
  472.     fl.l_len= 0;/* length, 0 = to EOF*/
  473.     fl.l_pid= getpid(); /* our PID*/
  474.    
  475.  
  476.     /* Primero comprobar con GETLK si hay un candado
  477.     , si no hay ni WR ni RD podemos obtenerlo nostros */
  478.     if (fcntl(fd, F_GETLK, &fl) == -1) {
  479.         /* Handle unexpected error */;
  480.         printf("Error getting lock, %i - %s\n", errno, strerror(errno));
  481.         exit(-1);
  482.     }
  483.     if(fl.l_type == F_WRLCK){
  484.         printf("Process %ld has a write lock already!\n", fl.l_pid);
  485.         printf("%i - %s\n", errno, strerror(errno));
  486.         exit(-1);
  487.     } else if (fl.l_type == F_RDLCK) {
  488.         printf("Process %ld has a read lock already!\n", fl.l_pid);
  489.         printf("%i - %s\n", errno, strerror(errno));
  490.         exit(-1);
  491.     }
  492.     if (fcntl(fd, F_SETLK, &fl) == -1) {
  493.        
  494.         perror("Fallo al obtener el candado");
  495.         exit(-1);
  496.        
  497.     } else { /* Lock was granted... */
  498.         /* Perform I/O on bytes 0 to EOF of file */
  499.         time_t tim;
  500.         tim = time(NULL);
  501.         struct tm * lt;
  502.         lt = localtime(&tim);
  503.         int MAX = 100;
  504.         const char * buf[MAX],* format = "Tiempo %T";
  505.         int length = strftime(buf, MAX, format, lt);
  506.         if(length == 0){
  507.             puts("Couldn't format time");
  508.             exit(EXIT_FAILURE);
  509.         }
  510.         write(fd, buf, length);
  511.         /* Unlock the locked bytes */
  512.         fl.l_type = F_UNLCK;
  513.         fl.l_whence = SEEK_SET;
  514.         fl.l_start = 0;
  515.         fl.l_len = 0;
  516.         if (fcntl(fd, F_SETLK, &fl) == -1){
  517.             /* Handle error */;
  518.             printf("Error removing lock, %i - %s\n", errno, strerror(errno));
  519.             exit(-1);
  520.         }
  521.     }
  522.     exit(EXIT_SUCCESS);
  523. }
  524. //----------------------------------------------------------------------
  525. //----------------7-PROCESOS--------------------------------------------
  526. /*planificador*/
  527. #include <sched.h>
  528. /*printf*/
  529. #include <stdio.h>
  530. /*getpriority*/
  531. #include <sys/time.h>
  532. #include <sys/resource.h>
  533.  
  534. int main(){
  535.  
  536.     int i = 0; /*pid proceso actual*/
  537.     int politica, nice;
  538.     struct sched_param p;
  539.    
  540.     /*Política del proceso*/
  541.     politica = sched_getscheduler(i);
  542.     /*Obtener la prioridad del proceso i a partir de p*/
  543.     sched_getparam(i,&p);
  544.     /*Nice del proceso*/
  545.     nice = getpriority(PRIO_PROCESS, i);
  546.  
  547.     if(politica == SCHED_FIFO)
  548.         printf("Política: SCHED_FIFO\n");
  549.     else if(politica == SCHED_RR)
  550.         printf("Política: SCHED_RR\n");
  551.     else if(politica == SCHED_OTHER)
  552.         printf("Política: SCHED_OTHER\n");
  553.     printf("Prioridad del proceso: %d\n", p.sched_priority);
  554.     printf("Nice del proceso: %d\n", nice);
  555.  
  556.     printf("Valor máximo de prioridad: %d\n", sched_get_priority_max(politica));
  557.     printf("Valor mínimo de prioridad: %d\n", sched_get_priority_min(politica));
  558.  
  559.  
  560.     return 0;
  561. }
  562.  
  563. //sesion e info-proceso
  564. #include <sys/types.h>
  565. #include <unistd.h>
  566. #include <stdio.h>
  567. #include <sys/time.h>
  568. #include <sys/resource.h>
  569.  
  570.  
  571. void ejercicio2(void){
  572.     pid_t pid, ppid, pgid, sid;
  573.     struct rlimit limit;
  574.     char dir [100];
  575.  
  576.     pid  = getpid();
  577.     ppid = getppid();
  578.     pgid = getpgid(pid);
  579.     sid  = getsid(pid);
  580.  
  581.     printf("pid  = %d\n",pid);
  582.     printf("ppid = %d\n",ppid);
  583.     printf("pgid = %d\n",pgid);
  584.     printf("sid  = %d\n",sid);
  585.     printf("RLIMIT_FSIZE = %d\n", getrlimit(RLIMIT_FSIZE, &limit));
  586.     printf("path = %s\n", getcwd(dir, 100));
  587. }
  588.  
  589.  
  590. void ejercicio3(void){
  591.     pid_t forked;
  592.  
  593.     printf("EJER3--------------\n");
  594.     forked = fork();
  595.  
  596.  
  597.     if (forked == -1){//Hijo   
  598.         perror("error fork");
  599.         //exit(-1);
  600.     }
  601.     else if (forked == 0){
  602.         printf("Nueva sesion = %d\n", setsid());
  603.         chdir("/tmp");
  604.         ejercicio2();
  605.     }
  606.     else{//Padre
  607.         int signal;
  608.         wait(&signal);
  609.     }
  610. }
  611.  
  612. int main(int argc, char** argv){
  613.  
  614.     ejercicio2();
  615.     ejercicio3();
  616.  
  617.     return 0;
  618. }
  619.  
  620. /* exec.c ­ Listar los procesos del usuario usando exec. */
  621. #include <stdio.h>
  622. #include <unistd.h>
  623. #include <stdlib.h>
  624. int main (){
  625.     int salida = 0;/* Salida del comando */
  626.     printf ("Ejemplo de exec.\n");
  627.     // execlp("ls", "ls", "­al", NULL);
  628.     execl ("/bin/ls", "ls", "­l", NULL);
  629.     printf ("Salida del comando: %d\n", salida);
  630. exit (salida);
  631. }
  632.  
  633. // System.c
  634. #include <stdlib.h>
  635.  
  636. int main(int argc, char** argv){
  637.     return system(argv[1]);
  638.     //    ./sys "ls ­l"
  639. }
  640.  
  641. //demonizar: dups, fork y exec
  642. #include <sched.h>
  643. #include <stdio.h>
  644. #include <unistd.h>
  645. #include <sys/time.h>
  646. #include <sys/resource.h>
  647. #include <sys/types.h>
  648. #include <sys/stat.h>
  649. #include <fcntl.h>
  650.  
  651.  
  652. //Prototipos
  653. void ejercicio2(void);
  654.  
  655. int main(int argc, char** argv){
  656.     int fdOut, fdErr, fdIn;
  657.    
  658.     pid_t pid = fork();
  659.  
  660.     if(pid == -1) perror("Error fork");
  661.     else if(pid == 0){
  662.         //$>cd /tmp; touch daemon.err daemon.out null
  663.         fdOut = open("/tmp/daemon.out", O_RDWR | O_CREAT);
  664.         fdErr = open("/tmp/daemon.err",O_RDWR | O_CREAT);
  665.         fdIn = open("/tmp/null",O_RDWR | O_CREAT);
  666.  
  667.         dup2(fdIn,STDIN_FILENO);
  668.         dup2(fdOut,STDOUT_FILENO);
  669.         dup2(fdErr,STDERR_FILENO);
  670.  
  671.         execv (argv[1],argv + 1);
  672.                 //o argv
  673.         close(fdErr);
  674.         close(fdOut);
  675.         close(fdIn);
  676.     }
  677.     else{
  678.         int status;
  679.         wait(&status);
  680.         printf("El comando termino de ejecutarse\n");
  681.     }
  682.     return 0;
  683. }
  684.  
  685. //señales con pending
  686. #include <signal.h>
  687. #include <stdio.h>
  688. #include <errno.h>
  689. #include <stdlib.h>
  690. #include <unistd.h>
  691.  
  692. /*Creo una variable en la terminal: SLEEP_SECS = 3
  693.  Luego exporto la variable: export SLEEP_SECS
  694.  Puedo compilar.*/
  695.  
  696. int main() {
  697.  
  698.     sigset_t mascara;
  699.     sigemptyset(&mascara);
  700.     sigaddset(&mascara, SIGINT);
  701.     sigaddset(&mascara, SIGTSTP);
  702.  
  703.     if (sigprocmask(SIG_BLOCK, &mascara, NULL) == -1) {
  704.         perror("No se puede borrar las señales");
  705.         return -1;
  706.     }
  707.     char *sleep_secs = getenv("SLEEP_SECS");
  708.     if (sleep_secs == NULL) {
  709.         printf("No se puede leer SLEEP_SECS\n");
  710.         return -1;
  711.     }
  712.  
  713.     int secs = atoi(sleep_secs);
  714.     if (secs < 0) secs = 0;
  715.    
  716.     sleep(secs);
  717.  
  718.     sigset_t pendiente;
  719.     sigemptyset(&pendiente);
  720.     if (sigpending(&pendiente) == -1) {
  721.         perror("No hay señales pendientes");
  722.         return -1;
  723.     }
  724.     switch (sigismember(&pendiente, SIGINT)) {
  725.         case 1:
  726.             printf("Se ha recibido SIGINT durante sleep\n");
  727.             break;
  728.         case -1:
  729.             perror("No hay señal pendiente SIGINT");
  730.             return -1;
  731.             break;
  732.     }
  733.     switch (sigismember(&pendiente, SIGTSTP)) {
  734.         case 1:
  735.             printf("Se ha recibido SIGTSTP durante sleep, desbloqueando señal...\n");
  736.             sigdelset(&mascara, SIGINT);
  737.             if (sigprocmask(SIG_UNBLOCK, &mascara, NULL) == -1) {
  738.                 perror("No se puede desbloquear las señales");
  739.                 return -1;
  740.             }
  741.             break;
  742.         case -1:
  743.             perror("No hay señal pendiente SIGTSTP");
  744.             return -1;
  745.             break;
  746.     }
  747.     printf("Termino el programa\n");
  748.  
  749.     return 0;
  750. }
  751.  
  752. /*señales con sigaction*/
  753. #include <signal.h>
  754. /*printf*/
  755. #include <stdio.h>
  756. #include <unistd.h>
  757.  
  758.  
  759. void handler(int signo){
  760.  
  761.     if(signo == SIGINT) printf("Señal SIGINT\n");
  762.     else if(signo == SIGTSTP) printf("Señal SIGTSTP\n");
  763.  
  764. }
  765.  
  766.  
  767. int main(){
  768.  
  769.  
  770.     sigset_t grupo;
  771.     struct sigaction sig;
  772.     sig.sa_flags = SA_RESTART;
  773.     sig.sa_handler = handler;
  774.  
  775.     sigemptyset(&grupo);
  776.     sigaddset(&grupo, SIGINT);
  777.     sigaddset(&grupo, SIGTSTP);
  778.  
  779.  
  780.     sigprocmask(SIG_BLOCK, &grupo, NULL);
  781.     printf("Señales bloqueadas.\n");
  782.    
  783.     sigaction(SIGINT, &sig, NULL); /*CTRL+C*/
  784.     sigaction(SIGTSTP, &sig, NULL); /*CTRL+Z*/
  785.    
  786.     sleep(10);
  787.  
  788.  
  789.     sigprocmask(SIG_UNBLOCK, &grupo, NULL);
  790.     printf("Señales desbloqueadas.\n");
  791.  
  792.     return 0;
  793. }
  794.  
  795. /*contador de señales*/
  796. #include <signal.h>
  797. /*printf*/
  798. #include <stdio.h>
  799. #include <unistd.h>
  800.  
  801. volatile int i;
  802.  
  803. void handler(int signo){
  804.     i = i + 1;
  805. }
  806.  
  807.  
  808. int main(){
  809.  
  810.     struct sigaction sig;
  811.     i = 0;
  812.     sig.sa_flags = SA_RESTART;
  813.     sig.sa_handler = handler;
  814.  
  815.     sigaction(SIGINT, &sig, NULL); /*CTRL+C*/
  816.     sigaction(SIGTSTP, &sig, NULL); /*CTRL+Z*/
  817.  
  818.     while(i < 10)
  819.     {
  820.         sleep(5);
  821.         printf("Número de señales: %d\n", i);
  822.        
  823.     }
  824.     return 0;
  825. }
  826.  
  827. /*señales sigusr-bomba: borrar ejecutable*/
  828. #include <signal.h>
  829. /*printf*/
  830. #include <stdio.h>
  831. /*perror*/
  832. #include <errno.h>
  833. /*unlink, alarm*/
  834. #include <unistd.h>
  835. /**/
  836. #include <string.h>
  837. #include <stdlib.h>
  838.  
  839. volatile int desac, alarma;
  840.  
  841. void handler(int signo){
  842.  
  843.     if(signo == SIGUSR1) desac = 1; /*destruccion desactivada*/
  844.     if(signo == SIGALRM) alarma = 1; /*alarma activada*/
  845.  
  846. }
  847.  
  848. int main(int argc, char **argv){
  849.  
  850.  
  851.     sigset_t grupo;
  852.     struct sigaction sig;
  853.     desac= 0;
  854.  
  855.     if (argc!=2) perror("Error: número de argumentos.\n");
  856.     sig.sa_flags = SA_RESTART;
  857.     sig.sa_handler = handler;
  858.  
  859.     sigfillset(&grupo);
  860.     sigdelset(&grupo, SIGUSR1);
  861.     sigdelset(&grupo, SIGALRM);
  862.  
  863.  
  864.     sigaction(SIGUSR1, &sig, NULL); /*ctr+u*/
  865.     sigaction(SIGALRM, &sig, NULL);
  866.    
  867.     alarm(atoi(argv[1]));
  868.     sigsuspend(&grupo);
  869.     if(desac)
  870.     {  
  871.         printf("Autodestrucción desactivada.\n");
  872.         return -1;
  873.     }
  874.     if(alarma) unlink(argv[0]);
  875.  
  876.     return 0;
  877. }
  878. //----------------------------------------------------------------------
  879. //----------------8-pipes-----------------------------------------------
  880. //-----------: man -L en pipe | tail -n 60 > pipe.c --------------------
  881. //pipes y exec
  882. #include <stdio.h>
  883. #include <unistd.h>
  884. #include <sys/types.h>
  885. #include <sys/wait.h>
  886.  
  887. #define PW 1
  888. #define PR 0
  889.  
  890. int main(int argc, char** argv){
  891.     int tuberia[2];
  892.     pid_t pid;
  893.  
  894.     pipe(tuberia);
  895.    
  896.     pid = fork();
  897.     if(pid == -1) perror("Error de pid.\n");
  898.     else if(pid == 0) /*hijo*/
  899.     {  
  900.         close(tuberia[PW]);
  901.         dup2(tuberia[PR], 0);
  902.         close(tuberia[PR]);
  903.         execlp(argv[3],argv[3],argv[4],NULL);
  904.         //perror(argv[0]);
  905.         printf("HIJO.\n");
  906.     }
  907.     else /*padre*/
  908.     {
  909.         close(tuberia[PR]);
  910.         dup2(tuberia[PW], 1);
  911.         close(tuberia[PW]);
  912.         execlp(argv[1],argv[1],argv[2],NULL);
  913.         //perror(argv[0]);
  914.         printf("PADRE.\n");
  915.     }
  916.     waitpid(pid, NULL, 0);
  917.     return 0;
  918. }
  919.  
  920. //pipe bidireccional
  921. #include <stdio.h>
  922. #include <unistd.h>
  923. #include <sys/types.h>
  924. #include <sys/wait.h>
  925. #include <string.h>
  926. #include <stdlib.h>
  927.  
  928. #define PW 1
  929. #define PR 0
  930.  
  931. //Ejemplo DE PIPES man -L en pipe
  932. int main(int argc, char** argv){
  933.     int tuberia1[2], tuberia2[2], readb;
  934.     pid_t pid;
  935.    
  936.     int num = 0;
  937.    
  938.     pipe(tuberia1);
  939.     pipe(tuberia2);
  940.  
  941.     pid = fork();
  942.     if(pid == -1) perror("Error de pid.\n");
  943.     else if(pid == 0) /*hijo*/
  944.     {  
  945.         char buffer[256];
  946.         char mensaje[1] = {'l'};
  947.         close(tuberia1[PW]);
  948.         close(tuberia2[PR]);
  949.         int i;
  950.         for(i = 0; i < 10; i++){
  951.             readb = read(tuberia1[PR], buffer,256);
  952.             buffer[readb] = '\0';
  953.             printf("[Hijo], mensaje leído: %s\n", buffer);
  954.             sleep(1);
  955.             if(i == 9) mensaje[0] = 'q';
  956.             write(tuberia2[PW], mensaje, 1);
  957.  
  958.         }
  959.         close(tuberia2[PW]);
  960.         close(tuberia1[PR]);
  961.         exit(0);
  962.     }
  963.     else /*padre*/
  964.     {
  965.         close(tuberia1[PR]);
  966.         close(tuberia2[PW]);
  967.         char buffer_p[256];
  968.         char mensaje_p[1] = {'l'};
  969.  
  970.         while(mensaje_p[0] != 'q'){
  971.             printf("[Padre], nuevo mensaje: ");
  972.             scanf("%s", buffer_p);
  973.             //readb = read(0, buffer_p,256);
  974.             //buffer_p[readb]= '\0';
  975.             write(tuberia1[PW], buffer_p, strlen(buffer_p));
  976.             while(mensaje_p[0] != 'l' && mensaje_p[0]!= 'q'){          
  977.                 read(tuberia2[PR], mensaje_p,1);
  978.             }
  979.            
  980.         }
  981.         close(tuberia1[PW]);
  982.         close(tuberia2[PR]);
  983.     }
  984.     waitpid(pid, NULL, 0);
  985.    
  986.     return 0;
  987. }
  988.  
  989. //----------------------------------------------------------------------
  990. //----------------9-Sockets---------------------------------------------
  991. //----: man -L en getaddrinfo | tail -n 200 > sockets.c ----------------
  992. //----------------------------------------------------------------------
  993. //tcp server con forks y evitar zombies
  994. #include <sys/types.h>
  995. #include <sys/wait.h>
  996. #include <stdio.h>
  997. #include <stdlib.h>
  998. #include <unistd.h>
  999. #include <string.h>
  1000. #include <sys/socket.h>
  1001. #include <netdb.h>
  1002.  
  1003. #define BUF_SIZE 50
  1004.  
  1005. int main(int argc, char *argv[])
  1006. {
  1007.     struct addrinfo hints;
  1008.     struct addrinfo *result, *rp;
  1009.     int sfd, s;
  1010.     struct sockaddr_storage peer_addr;
  1011.     socklen_t peer_addr_len;
  1012.     ssize_t nread;
  1013.     char buf[BUF_SIZE];
  1014.     int nhijos = 0;
  1015.  
  1016.     if (argc != 2) {
  1017.     fprintf(stderr, "Usage: %s port\n", argv[0]);
  1018.     exit(EXIT_FAILURE);
  1019.     }
  1020.  
  1021.     memset(&hints, 0, sizeof(struct addrinfo));
  1022.     hints.ai_family = AF_INET6;    /* Allow IPv4 or IPv6 */
  1023.     hints.ai_socktype = SOCK_STREAM; /* tcp socket; udp: SOCK_DGRAM */
  1024.     hints.ai_flags = AI_PASSIVE;    /* For wildcard IP address */
  1025.     hints.ai_protocol = 0;          /* Any protocol */
  1026.     hints.ai_canonname = NULL;
  1027.     hints.ai_addr = NULL;
  1028.     hints.ai_next = NULL;
  1029.  
  1030.     s = getaddrinfo(NULL, argv[1], &hints, &result);
  1031.     if (s != 0) {
  1032.     fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
  1033.     exit(EXIT_FAILURE);
  1034.     }
  1035.  
  1036.     for (rp = result; rp != NULL; rp = rp->ai_next) {
  1037.     sfd = socket(rp->ai_family, rp->ai_socktype,
  1038.            rp->ai_protocol);
  1039.     if (sfd == -1)
  1040.        continue;
  1041.     if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0)
  1042.        break;                  /* Success */
  1043.  
  1044.     close(sfd);
  1045.     }
  1046.  
  1047.     if (rp == NULL) {               /* No address succeeded */
  1048.     fprintf(stderr, "Could not bind\n");
  1049.     exit(EXIT_FAILURE);
  1050.     }
  1051.  
  1052.     freeaddrinfo(result);           /* No longer needed */
  1053.  
  1054.     /* Read datagrams and echo them back to sender */
  1055.     if(listen(sfd, 5)==-1){
  1056.             perror("Fallo de listen");
  1057.             exit(EXIT_FAILURE);
  1058.     }
  1059.     int cfd;
  1060.         for (;;) {
  1061.        
  1062.         peer_addr_len = sizeof(struct sockaddr_storage);
  1063.         cfd = accept(sfd, (struct sockaddr *) &peer_addr, &peer_addr_len);
  1064.        
  1065.         if(cfd == -1){
  1066.             perror("Fallo al accept");
  1067.             exit(-1);
  1068.         }
  1069.    
  1070.         pid_t pid;
  1071.         pid = fork();
  1072.        
  1073.         if(pid == 0){
  1074.            
  1075.             char host[NI_MAXHOST], service[NI_MAXSERV];
  1076.  
  1077.             s = getnameinfo((struct sockaddr *) &peer_addr,
  1078.                        peer_addr_len, host, NI_MAXHOST,
  1079.                        service, NI_MAXSERV, NI_NUMERICSERV);
  1080.             if (s == 0)
  1081.                printf("Conectado a %s:%s\n", host, service);
  1082.             else
  1083.                fprintf(stderr, "getnameinfo: %s\n", gai_strerror(s));
  1084.  
  1085.             while(1){
  1086.                    
  1087.                 nread = recv(cfd, buf, BUF_SIZE, 0);
  1088.                 if (nread == -1){
  1089.                     perror("Fallo al receive");
  1090.                     exit(EXIT_FAILURE);
  1091.                 }
  1092.                
  1093.                 buf[nread] = '\0';
  1094.            
  1095.                 printf("pid(%i): %s",getpid(),buf);//Viene \n en al leer el echo en el cliente
  1096.                
  1097.                 if (send(cfd, buf, strlen(buf), 0) == -1){
  1098.                    fprintf(stderr, "Error sending response\n");
  1099.                    exit(EXIT_FAILURE);
  1100.                 }
  1101.                 if(strcmp("q\n", buf)==0){
  1102.                     exit(EXIT_SUCCESS);
  1103.                 }
  1104.        
  1105.             }
  1106.         }else if(pid == -1){
  1107.             perror("Fallo en el fork");
  1108.             exit(EXIT_FAILURE);
  1109.         }else{
  1110.                 nhijos++;
  1111.                 close(cfd);
  1112.         }
  1113.     }
  1114.     int i = 0;
  1115.     int status;
  1116.     while(i<=nhijos){
  1117.             wait(&status);
  1118.             i++;
  1119.     }
  1120.     exit(EXIT_SUCCESS);
  1121. }
  1122.  
  1123. //tcp client
  1124.  
  1125. #include <sys/types.h>
  1126. #include <sys/socket.h>
  1127. #include <netdb.h>
  1128. #include <stdio.h>
  1129. #include <stdlib.h>
  1130. #include <unistd.h>
  1131. #include <string.h>
  1132.  
  1133. #define BUF_SIZE 50
  1134.  
  1135. int
  1136. main(int argc, char *argv[])
  1137. {
  1138.    struct addrinfo hints;
  1139.    struct addrinfo *result, *rp;
  1140.    int sfd, s, j;
  1141.    size_t len;
  1142.    ssize_t nread;
  1143.    char buf[BUF_SIZE];
  1144.  
  1145.    if (argc < 3) {
  1146.        fprintf(stderr, "Usage: %s host port msg...\n", argv[0]);
  1147.        exit(EXIT_FAILURE);
  1148.    }
  1149.  
  1150.    /* Obtain address(es) matching host/port */
  1151.  
  1152.    memset(&hints, 0, sizeof(struct addrinfo));
  1153.    hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
  1154.    hints.ai_socktype = SOCK_STREAM; /* tcp socket;udp: SOCK_DGRAM */
  1155.    hints.ai_flags = 0;
  1156.    hints.ai_protocol = 0;          /* Any protocol */
  1157.  
  1158.    s = getaddrinfo(argv[1], argv[2], &hints, &result);
  1159.    if (s != 0) {
  1160.        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
  1161.        exit(EXIT_FAILURE);
  1162.    }
  1163.  
  1164.    /* getaddrinfo() returns a list of address structures.
  1165.       Try each address until we successfully connect(2).
  1166.       If socket(2) (or connect(2)) fails, we (close the socket
  1167.       and) try the next address. */
  1168.  
  1169.    for (rp = result; rp != NULL; rp = rp->ai_next) {
  1170.        sfd = socket(rp->ai_family, rp->ai_socktype,
  1171.                     rp->ai_protocol);
  1172.        if (sfd == -1)
  1173.            continue;
  1174.  
  1175.        if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
  1176.             break;                  /* Success */
  1177.  
  1178.        close(sfd);
  1179.    }
  1180.  
  1181.    if (rp == NULL) {               /* No address succeeded */
  1182.        fprintf(stderr, "Could not connect\n");
  1183.        exit(EXIT_FAILURE);
  1184.    }
  1185.  
  1186.    freeaddrinfo(result);           /* No longer needed */
  1187.  
  1188.    /* Send remaining command-line arguments as separate
  1189.       datagrams, and read responses from server */
  1190.    
  1191.     while(1){
  1192.       s = read(0, buf, BUF_SIZE);
  1193.       if(s == -1){
  1194.             perror("Falla el read de stdin");
  1195.       }
  1196.      
  1197.       buf[s] = '\0';
  1198.      
  1199.        if (write(sfd, buf, strlen(buf)) == -1) {
  1200.            fprintf(stderr, "failed write\n");
  1201.            exit(EXIT_FAILURE);
  1202.        }
  1203.  
  1204.        nread = read(sfd, buf, BUF_SIZE);
  1205.        if (nread == -1) {
  1206.            perror("Fallo al leer respuesta del servidor");
  1207.            exit(EXIT_FAILURE);
  1208.        }
  1209.    
  1210.        buf[nread] = '\0';
  1211.         if(strcmp("q\n", buf)==0)
  1212.             exit(EXIT_SUCCESS);
  1213.  
  1214.     }
  1215.    
  1216. }
  1217.  
  1218. //Servidor UDP + select (recibe ordenes de stdin)
  1219. #include <sys/types.h>
  1220. #include <stdio.h>
  1221. #include <stdlib.h>
  1222. #include <unistd.h>
  1223. #include <string.h>
  1224. #include <sys/socket.h>
  1225. #include <netdb.h>
  1226. #include <time.h>
  1227. #include <sys/time.h>
  1228.  
  1229.  
  1230.  
  1231. #define BUF_SIZE 500
  1232. #define MAX_OUTPUT_SIZE 50
  1233.  
  1234. int main(int argc, char *argv[])
  1235. {
  1236.    struct addrinfo hints;
  1237.    struct addrinfo *result, *rp;
  1238.    int sfd, s;
  1239.    struct sockaddr_storage peer_addr;
  1240.    socklen_t peer_addr_len;
  1241.    ssize_t nread;
  1242.    char buf[2];  
  1243.    struct timeval tv;
  1244.  
  1245.    if (argc != 2) {
  1246.        fprintf(stderr, "Usage: %s port\n", argv[0]);
  1247.        exit(EXIT_FAILURE);
  1248.    }
  1249.  
  1250.    memset(&hints, 0, sizeof(struct addrinfo));
  1251.    hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
  1252.    hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
  1253.    hints.ai_flags = AI_PASSIVE;    /* For wildcard IP address */
  1254.    hints.ai_protocol = 0;          /* Any protocol */
  1255.    hints.ai_canonname = NULL;
  1256.    hints.ai_addr = NULL;
  1257.    hints.ai_next = NULL;
  1258.  
  1259.    s = getaddrinfo(NULL, argv[1], &hints, &result);
  1260.    if (s != 0) {
  1261.        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
  1262.        exit(EXIT_FAILURE);
  1263.    }
  1264.  
  1265.    /* getaddrinfo() returns a list of address structures.
  1266.       Try each address until we successfully bind(2).
  1267.       If socket(2) (or bind(2)) fails, we (close the socket
  1268.       and) try the next address. */
  1269.  
  1270.    for (rp = result; rp != NULL; rp = rp->ai_next) {
  1271.        sfd = socket(rp->ai_family, rp->ai_socktype,
  1272.                rp->ai_protocol);
  1273.                
  1274.        if (sfd == -1)
  1275.            continue;
  1276.  
  1277.        if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0)
  1278.            break;                  /* Success */
  1279.  
  1280.        close(sfd);
  1281.    }
  1282.  
  1283.    if (rp == NULL) {               /* No address succeeded */
  1284.        fprintf(stderr, "Could not bind\n");
  1285.        exit(EXIT_FAILURE);
  1286.    }
  1287.  
  1288.    freeaddrinfo(result);           /* No longer needed */
  1289.  
  1290.    /* Read datagrams and echo them back to sender */
  1291.    
  1292.     tv.tv_sec = 2;
  1293.     tv.tv_usec = 0;
  1294.    
  1295.     while( buf[0] != 'q'){
  1296.  
  1297.         fd_set fset;
  1298.         FD_ZERO(&fset);
  1299.         FD_SET(0,&fset);
  1300.         FD_SET(sfd, &fset);
  1301.        
  1302.         s = select(sfd+1, &fset, NULL, NULL, &tv);
  1303.         if(s > 0){
  1304.            
  1305.             if(FD_ISSET(sfd, &fset)){
  1306.                 peer_addr_len = sizeof(struct sockaddr_storage);
  1307.                 nread = recvfrom(sfd, buf, sizeof(buf), 0,(struct sockaddr *) &peer_addr, &peer_addr_len);
  1308.                 if (nread == -1){
  1309.                     perror("Fallo al receive");
  1310.                     exit(EXIT_FAILURE);  
  1311.                 }
  1312.                  char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];
  1313.                  if (getnameinfo((struct sockaddr *)&peer_addr, peer_addr_len, hbuf, sizeof(hbuf), sbuf,
  1314.                                     sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV) == 0)
  1315.                     printf("host=%s, serv=%s\n", hbuf, sbuf);
  1316.                
  1317.             }else if(FD_ISSET(0,&fset)){
  1318.                     s = read(0, buf, 2);
  1319.                     if(s < 0){
  1320.                         perror("Fallo al leer comando de stdin");
  1321.                     }  
  1322.             }
  1323.            
  1324.             if(buf[0]=='t' || buf[0]=='d'){
  1325.                     time_t t;
  1326.                     char now[MAX_OUTPUT_SIZE];
  1327.                     time(&t);
  1328.                     struct tm* timedata = localtime(&t);
  1329.                    
  1330.                     if(buf[0]=='t'){
  1331.                         printf("Solicitud de hora\n");
  1332.                         strftime(now, MAX_OUTPUT_SIZE, "%H:%M", timedata);
  1333.                     }else{
  1334.                         printf("Solicitud de fecha\n");
  1335.                         strftime(now, MAX_OUTPUT_SIZE, "%d de %B del %Y", timedata);
  1336.                     }
  1337.                     if(FD_ISSET(sfd, &fset)){
  1338.                         if(sendto(sfd, now, strlen(now), 0, (struct sockaddr *) &peer_addr, peer_addr_len)==-1){
  1339.                                 perror("Fallo al send");
  1340.                                 exit(EXIT_FAILURE);
  1341.                         }
  1342.                     }else{
  1343.                         printf("%s\n",now);
  1344.                     }
  1345.                 }else if(buf[0] == 'q'){
  1346.                     printf("Conexion cerrada.\n");
  1347.                    
  1348.                    
  1349.                 }else{
  1350.                     printf("Comando desconocido\n");
  1351.                 }
  1352.            
  1353.         }
  1354.     }
  1355.    exit(EXIT_SUCCESS);
  1356. }
  1357. //----------------------------------------------------------------------
  1358. //----: man -L en getaddrinfo | tail -n 200 > sockets.c ----------------
  1359. //Ojo:
  1360. //-Ejemplo UDP. Cambiar hints.socktype a SOCK_STREAM para tcp-----------
  1361. //-hints.ai_family = AF_INET6 //evitar que se utilizen siempre ipv4-----
  1362.  
  1363. //-----------: man -L en pipe | tail -n 60 > pipe.c --------------------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement