archive-org.com » ORG » N » NETBSD.ORG

Total: 1243

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • basic unix programming
    in date time than hello o If this is not the case it will not have to rebuild hello o as obviously the file hasn t been modified If the file is newer it will have to rebuild hello o from hello c When Make has determined that it must build a target it will look at the indented lines with a tab directly following the target line These are the command it will execute in sequence expecting the target file to be a result of executing these commands If you wish to build a particular file only just type make where target is the name of the target you wish to build Now we ll conclude with a bigger example of a Makefile Assign variables Doing this makes the Makefile easier to modify if a path is incorrect or another compiler is used LINKFLAGS L usr X11R6 lib R usr X11R6 lib NB Don t assign CC like many linux folks do it makes impossible to use another compiler without changing the source If an all target is present it is always executed by default when you just type make even if it s not the first target all myprog In the following CC will expand to the contents of the variable CC myprog first o second o CC LINKFLAGS lX11 first o second o o myprog first o first c CC c first c second o second c CC c second c As you can see you can do rather interesting things with Make Consider using BSD Make scripts they simplify handling projects a lot System builds using them Using BSD Make Makefiles are nice but typing the same lines all the time can get very annoying even if you use SUFFIXES BSD s Make is a very nice Make which comes pre packed with some files which can make your life a lot easier and your Makefiles more elegant but it is not compatible with GNU make Some things are even incompatible between the Makes of different versions of BSD Now we got that out of the way let s see an example PROG test SRCS test a c test b c We have written no manpage yet so tell Make not to try and build it from nroff sources If you do have a manpage you usually won t need this line since the default name of the manpage is PROG 1 MAN include bsd prog mk That s all there s to it Put this in the same directory as the test program s sources and you re good to go If you re on a non BSD system chances are that the normal make program will choke on this file In that case the BSD Make might be installed as pmake or bmake On Mac OS X BSD make is called bsdmake the default make is GNU Make If you can t find make on your particular system ask your administrator about it The

    Original URL path: http://wiki.netbsd.org/examples/basic_unix_programming/ (2016-02-01)
    Open archived version from archive

  • configuration examples
    list Ports History Emulators Packages Browse packages Release engineering Wiki Home Edit Comment Source History New RecentChanges NetBSD Wiki examples configuration examples This article aims to show configuration examples for common configurations Configuration examples for login conf sysctl conf or specific parameters required to newfs for particular setups belong here but the article should not become a configuration files gallery for every setup It also does not aim to explain every detail of the configuration Links should be provided to the relevant detailed documentation For performance oriented configuration details also see Tuning NetBSD for performance This article is a work in progress Desktop PC Generally desktop systems run applications which heavily require executable and stack pages Part of the file buffer cache may be sacrificed in most cases to permit the system to keep more executable pages in live memory sysctl conf vm execmin 14 vm filemin 1 vm execmax 70 vm filemax 10 kern maxvnodes 32768 login conf default datasize 256M memoryuse 256M stacksize 64M maxproc 2048 openfiles 2048 priority 1 kernel configuration options SHMMAXPGS 32768 2048 pages is the default Database server PostgreSQL PostgreSQL recommends the following in its documentation options SYSVSHM options SHMMAXPGS 4096 options SHMSEG 256

    Original URL path: http://wiki.netbsd.org/examples/configuration_examples/ (2016-02-01)
    Open archived version from archive

  • drvctlio
    include string h include stdlib h include fcntl h int main int argc char argv struct devlistargs l unsigned int i children int drvfd if argc 2 err 1 args if drvfd open DRVCTLDEV O RDONLY 0 0 err 1 can t open DRVCTLDEV strlcpy l l devname argv 1 sizeof l l devname l l childname NULL l l children 0 if ioctl drvfd DRVLISTDEV l 1 err 1

    Original URL path: http://wiki.netbsd.org/examples/drvctlio/ (2016-02-01)
    Open archived version from archive

  • elf executables for powerpc
    the use of registers These conventions require the code to save r31 but not r9 The bl puts instruction is our evidence that the program calls puts 3 instead of printf 3 The compiler did not optimize the above code Some optimizations might be obvious Consider the code that saves argc and argv to the stack We would can use r1 instead of copying r1 to r11 Going further we would can delete the code and never save argc and argv because this main function never uses argc and argv Optimizing the main function Expect a compiler like gcc to write better assembly code than a human programmer who knows assembly language The best way to optimize the assembly code is to enable some gcc optimization flags Released software often uses the O2 flag so here is a commented copy of greetings s from the gcc of NetBSD 4 0 1 macppc with O2 in use This is a commented version of the optimized assembly output from cc O2 mregnames S greetings c file greetings c Our string constant is now in a section that would allow an ELF linker to remove duplicate strings See the info as documentation for the section directive section rodata str1 4 aMS progbits 1 align 2 LC0 string Greetings Earth Enter the text section and declare main as before section text align 2 globl main type main function main We use registers as before r1 stack pointer r3 argc r4 argv lr return address r3 int return value Set r0 lr so that we can save lr later mflr r0 r0 lr Allocate only 16 bytes for our stack frame and point r1 0 to the previous stack frame stwu r1 16 r1 r1 16 r1 r1 16 Save lr in the lr save word at r1 0 0 r1 20 before calling puts LC0 lis r3 LC0 ha la r3 LC0 l r3 r3 LC0 stw r0 20 r1 r1 20 r0 bl puts puts r3 Restore lr free stack frame and return 0 lwz r0 20 r1 r0 r1 20 li r3 0 r3 0 addi r1 r1 16 r1 r1 16 mtlr r0 lr r0 blr return r3 This main function is smaller than before but ELF wants to know the size size main main ident GCC GNU 4 1 2 20061021 prerelease NetBSD nb3 20061125 The optimized version of the main function does not use the r9 r11 or r31 registers and it does not save r31 argc or argv to the stack The stack frame occupies only 16 bytes not 32 bytes The main function barely uses the stack frame only writing the frame pointer to 0 r1 and never reading anything The main function must reserve 4 bytes of space at 4 r1 for an lr save word in case the puts function saves its link register The frame pointer and lr save word together occupy 8 bytes of stack space The main function allocates 16 bytes instead of only 8 bytes because of a convention that the stack pointer is a multiple of 16 The relocatable object file Now that we have the assembly code there are two more steps before we have the final executable The first step is to run the assembler as which translates the assembly code to machine code and stores the machine code in an ELF relocatable object The second step is to run the linker ld which combines some ELF relocatables into one ELF executable There are various tools that can examine ELF files The command nm 1 lists the global symbols in an object file The commands objdump 1 and readelf 1 show other information These commands can examine both relocatables and executables Though the executable is more interesting the relocatable is simpler To continue our example we can run the assembler with greetings s to produce greetings o We use the optimized code in greetings s from cc O2 mregnames S greetings c because it was shorter We feed our file greeting s to usr bin as with a simple command as o greetings o greetings s The output greetings o is a relocatable object file and file 1 confirms this file greetings o greetings o ELF 32 bit MSB relocatable PowerPC or cisco 4500 version 1 SYSV not stripped List of sections The source greetings s had assembler directives for two sections rodata str1 4 and text so the ELF relocatable greetings o should contain those two sections The command objdump can list the sections objdump Usage objdump option s file s Display information from object file s At least one of the following switches must be given h section headers Display the contents of the section headers objdump h greetings o greetings o file format elf32 powerpc Sections Idx Name Size VMA LMA File off Algn 0 text 0000002c 00000000 00000000 00000034 2 2 CONTENTS ALLOC LOAD RELOC READONLY CODE 1 data 00000000 00000000 00000000 00000060 2 0 CONTENTS ALLOC LOAD DATA 2 bss 00000000 00000000 00000000 00000060 2 0 ALLOC 3 rodata str1 4 00000014 00000000 00000000 00000060 2 2 CONTENTS ALLOC LOAD READONLY DATA 4 comment 0000003c 00000000 00000000 00000074 2 0 CONTENTS READONLY This command verifies the presence of the text and rodata str1 4 sections The text section begins at file offset 0x34 and has size 0x2c in bytes The rodata str1 4 section begins at file offset 0x60 and has size 0x14 Because the source greetings s does not have assembler directives for the data or bss or comment section there must be another explanation for those three sections The data and bss section has size 0x0 Perhaps for traditional reasons the assembler puts these sections into every object file Because the source greeting s never mentioned the data or bss section nor allocated space in them so the assembler output them as empty sections The a out 5 format always had text data and bss segments The elf 5 format distinguishes segments and sections and also allows for arbitrary sections like rodata str1 4 and comment That leaves the mystery of the comment section The objdump command accepts j to select a section and s to show the contents so objdump j comment s greetings o dumps the 0x3c bytes in that section objdump j comment s greetings o greetings o file format elf32 powerpc Contents of section comment 0000 00474343 3a202847 4e552920 342e312e GCC GNU 4 1 0010 32203230 30363130 32312070 72657265 2 20061021 prere 0020 6c656173 6520284e 65744253 44206e62 lease NetBSD nb 0030 33203230 30363131 32352900 3 20061125 This is just the string fromm the ident assembler directive between a pair of 0 bytes So whenever gcc generates an ident directive the assembler leaves this comment section to identify the compiler that produced this relocatable The info as documentation for the ident directive shipped with NetBSD 4 0 1 continues to claim that the assembler does not actually emit anything for it but in fact the assembler emits this comment section The objdump tool also has a disassembler through its d option Disassembly is the reverse process of assembly it translates machine code to assembly code We would can disassemble greetings o but the output would have a few defects because of symbols that lack their final values Of symbols and addresses Our assembly code in greetings s had three symbols The first symbol had the name LC0 and pointed to our string LC0 string Greetings Earth The second symbol had the name main It was a global symbol that pointed to a function globl main type main function main mflr r0 The third symbol had the name puts Our code used puts in a function call though it never defined the symbol bl puts A symbol has a name and an integer value In assembly code a symbol acts as a constant inline integer The very most common use of a symbol is to hold an address pointing to either a function or a datum When a symbol appears as an operand to an instruction the assembler would inline the value of that symbol into the machine code The problem is that the assembler often does not know the final value of the symbol So the assembler as saves some information about symbols into the ELF file The linker ld can use this information to relocate symbols to their final values resolve undefined symbols and inline the final values into the machine code The fact that ld relocates symbols is also the reason that o files are relocatable objects The nm command shows the names of symbols in an object file The output of nm shows that greetings o contains only two symbols The LC0 symbol is missing nm greetings o 00000000 T main U puts The nm tool comes from Unix tradition and remains a great way to check the list of symbols For each symbol nm displays the hexadecimal value a single letter for the type then the name The letter T marks symbols that point into a text section either the text section or some other arbitrary section of executable code The letter U marks undefined symbols which do not have a value The nm tool claims that symbol main has address 0x00000000 which to be a useless value The actual meaning is that main points to offset 0x0 within section text A more detailed view of the symbol table would provide evidence of this Fate of symbols The machine code in greetings o is incomplete If the address of the string Greetings Earth is not zero then something must fix the instructions at 0x8 and 0xc To avoid an infinite loop something must fix the instruction at 0x14 to find the function puts The linker will have the task to edit and finish the machine code Because this part of the wiki page now comes before the part about machine code this disassembly should probably not be here 00000000 main 0 31 00000 01000 02a6 mflr r0 4 37 00001 00001 fff0 stwu r1 16 r1 8 15 00011 00000 0000 lis r3 0 c 14 00011 00011 0000 addi r3 r3 0 10 36 00000 00001 0014 stw r0 20 r1 14 18 00000 00000 0001 bl 14 main 0x14 18 32 00000 00001 0014 lwz r0 20 r1 1c 14 00011 00000 0000 li r3 0 20 14 00001 00001 0010 addi r1 r1 16 24 31 00000 01000 03a6 mtlr r0 28 19 10100 00000 0020 blr The above disassembly does not tell that the code at 0x8 0xc and 0x14 is incomplete though the infinite loop at 0x14 is a hint There must be another way to find where the above code uses a symbol that lacks a final value The ELF relocatable greetings o bears information about both relocating symbols and resolving undefined symbols some uses of objdump or readelf can reveal this information ELF like any object format allows for a symbol table The list of symbols from nm greetings o is only an incomplete view of this table nm greetings o 00000000 T main U puts The command objdump t shows the symbol table in more detail objdump t greetings o greetings o file format elf32 powerpc SYMBOL TABLE 00000000 l df ABS 00000000 greetings c 00000000 l d text 00000000 text 00000000 l d data 00000000 data 00000000 l d bss 00000000 bss 00000000 l d rodata str1 4 00000000 rodata str1 4 00000000 l d comment 00000000 comment 00000000 g F text 0000002c main 00000000 UND 00000000 puts The first column is the value of the symbol in hexadecimal By some coincidence every symbol in greetings o has the value zero The second column gives letter l for a local symbol or letter g for a global symbol The third column gives the type of symbol with d for a debugging symbol lowercase f for a filename or uppercase F for a function symbol The fourth column gives the section of the symbol or ABS for an absolute symbol or UND for an undefined symbol The fifth column gives the size of the symbol in hexadecimal The sixth column gives the name of the symbol The filename symbol greetings c exists because the assembly code greetings s had a directive file greetings c The symbol main has a nonzero size because of the size directive Each section of this ELF relocatable has a symbol that points to address 0x0 in the section Then every section of this relocatable must contain address 0x0 A view of the section headers in greetings o confirms that every section begins at address 0x0 objdump h greetings o greetings o file format elf32 powerpc Sections Idx Name Size VMA LMA File off Algn 0 text 0000002c 00000000 00000000 00000034 2 2 CONTENTS ALLOC LOAD RELOC READONLY CODE 1 data 00000000 00000000 00000000 00000060 2 0 CONTENTS ALLOC LOAD DATA 2 bss 00000000 00000000 00000000 00000060 2 0 ALLOC 3 rodata str1 4 00000014 00000000 00000000 00000060 2 2 CONTENTS ALLOC LOAD READONLY DATA 4 comment 0000003c 00000000 00000000 00000074 2 0 CONTENTS READONLY The output of objdump h shows the address of each section in the VMA and LMA columns ELF files always use the same address for both VMA and LMA All five sections in greetings o begin at address 0x0 Thus all four sections marked ALLOC would overlap in memory The linker will must relocate these four sections so that they do not overlap The value of each symbol is the address The section of each symbol serves to disambiguate addresses where sections overlap Thus symbol main points to address 0x0 in the section text not any other section Because every section begins at address 0x0 each address is relative to the beginning of the section Therefore symbol main points to offset 0x0 into the section text TODO explain relocation records objdump r greetings o greetings o file format elf32 powerpc RELOCATION RECORDS FOR text OFFSET TYPE VALUE 0000000a R PPC ADDR16 HA rodata str1 4 0000000e R PPC ADDR16 LO rodata str1 4 00000014 R PPC REL24 puts Disassembly and machine code Disassembly GNU binutils provide both assembly and the reverse process disassembly While as does assembly objdump d does disassembly Both programs use the same library of opcodes By default objdump d disassembles all executable sections The j option can select a section to disassemble Our example relocatable greetings o has only executable section so j text becomes optional The disassembler works better with linked executable files It can also disassemble relocatables like greetings The output will confuse the reader because of undefined symbols and symbols not relocated to their final values objdump d greetings o greetings o file format elf32 powerpc Disassembly of section text 00000000 main 0 7c 08 02 a6 mflr r0 4 94 21 ff f0 stwu r1 16 r1 8 3c 60 00 00 lis r3 0 c 38 63 00 00 addi r3 r3 0 10 90 01 00 14 stw r0 20 r1 14 48 00 00 01 bl 14 main 0x14 18 80 01 00 14 lwz r0 20 r1 1c 38 60 00 00 li r3 0 20 38 21 00 10 addi r1 r1 16 24 7c 08 03 a6 mtlr r0 28 4e 80 00 20 blr The disassembled code has a slightly different syntax Every instruction has a label and each label is the hexadecimal address The hex after each label is the machine code for that instruction The syntax is more ambiguous so register names do not begin with a sign r3 can be a register instead of a symbol and 14 can be a label instead of an immediate value The size of every PowerPC instruction is four bytes PowerPC architecture requires this fixed width of four bytes or 32 bits for every instruction It also requires an alignment of four bytes for every instruction meaning that the address of every instruction is a multiple of four The above code meets both requirements The disassembled code would must resemble the assembly code in greetings s A comparison shows that every instruction is the same except for three instructions Address 0x8 has lis r3 0 instead of lis r3 LC0 ha Address 0xc has addi r3 r3 0 instead of la r3 LC0 l r3 Address 0x14 has bl 14 main 0x14 instead of bl puts The fate of the symbols LC0 and puts would explain these differences The linker will inline the correct values of LC0 and puts so that these three instructions have sense Because we have the source file greeting s we know about the LC0 and puts symbols If the reader of objdump d greetings o would not know about these symbols then the three instructions at 0x8 0xc and 0x14 would seem strange useless and wrong The load immediate shifted lis instruction shifts the immediate value leftward by 16 bits then loads the register with the shifted value So lis r3 0 shifts zero leftward by 16 bits but the shifted value remains zero The unnecessary shift seems strange but it is not a problem The add immediate addi instruction does addition so addi r3 r3 0 increments r3 by zero which effectively does nothing The instruction seems unnecessary and useless The instruction at address 0x14 is bl 14 main 0x14 which branches to label 14 effectively forming an infinite loop because it branches to itself Something is wrong If the reader understands that the infinite loop is actually a branch to function puts then the function call still seems wrong because puts uses the argument in r3 and the code loads r3 with zero Therefore the function call might be puts NULL or puts main Zero is the null pointer and also the address of the main function but function puts wants the address of some string Before the linker relocates some things away from zero now

    Original URL path: http://wiki.netbsd.org/examples/elf_executables_for_powerpc/ (2016-02-01)
    Open archived version from archive

  • netbsd assembly
    mov eax 0x01 SYS exit push 0x00 exit int status push 0x00 int 0x80 How to compile and link To use the above codes you need to compile and then link them nasm f elf hello asm ld o hello hello o hello Hello world gas the portable GNU assembler It uses AT T syntax and designed after the 4 2BSD assembler You can use it on many CPU architectures Example section note netbsd ident a long 2f 1f long 4f 3f long 1 1 asciz NetBSD 2 p2align 2 3 long 400000000 4 p2align 2 section data data items this is an array long 3 39 41 21 42 34 42 23 38 37 15 37 16 17 18 25 23 12 31 2 set DATASIZE data items 4 1 section text globl start start movl 0 edi zero the index register movl DATASIZE ecx set ecx to number of items movl data items ecx 4 eax load first item movl eax ebx its the biggest atm main loop decl ecx decrement counter movl data items ecx 4 eax step to next element cmpl eax ebx is it greater cmovll eax ebx set ebx to greater if its less than cur num jecxz end prog if we are at item 0 end iterat ion jmp main loop again end prog pushl ebx return largest number pushl ebx BSD ism has to push twice movl 1 eax call exit int 0x80 kernel ret powerpc PowerPC processors appear inside multiple different hardware platforms NetBSD has at least 11 ports see Platforms The easiest way to obtain a PowerPC machine is probably to acquire a used Macintosh choosing from among the supported models for NetBSD macppc PowerPC processors have 32 bit registers and pointers and use big endian byte order A very few boards not with NetBSD run the PowerPC in little endian mode to match the hardware A few PowerPC processors also have a 64 bit mode NetBSD 5 0 will support some Apple G5 machines with these processors but only in 32 bit mode see ppcg5 project gas Here is an example of a program for gas factorial s This program is in the public domain and has no copyright This is an example of an assembly program for NetBSD powerpc It computes the factorial of NUMBER using unsigned 32 bit integers and prints the answer to standard output set NUMBER 10 section note netbsd ident a ELF note to identify me as a native NetBSD program type 0x01 desc NetBSD Version from sys param h int 7 length of name int 4 length of desc int 0x01 type ascii NetBSD 0 name ascii 0 padding int 500000003 desc section data decbuffer fill 16 buffer for decimal ASCII decbufend ascii n newline at end of ASCII section text PowerPC instructions need an alignment of 4 bytes balign 4 globl start type start function start compute factorial in r31 li r0 NUMBER mtctr r0 ctr number li r31 1 r31 factorial

    Original URL path: http://wiki.netbsd.org/examples/netbsd_assembly/ (2016-02-01)
    Open archived version from archive

  • proplib
    History New RecentChanges NetBSD Wiki examples proplib Proplib is an API lib to create handle and store property lists It was created by Apple but NetBSD also have a clean room implementation in the system and it s mostly used for implementing sysctl interfaces It s a somehow limited implementation to make it faster smaller maybe extended in the future as demands grow Here s a little example code to show some of the basics This will create a dictionary and store it as an xml file on the disk int main void prop dictionary t d bool r d prop dictionary create if d NULL goto error r prop dictionary set cstring d name Adam if r goto error r prop dictionary set uint32 d year 1986 if r goto error r prop dictionary externalize to file d test plist if r goto error return EXIT SUCCESS error fprintf stderr error n return EXIT FAILURE And this will read it and display the values int main void prop dictionary t d uint32 t year char name bool r d prop dictionary internalize from file test plist if d NULL goto error r prop dictionary get cstring d name name

    Original URL path: http://wiki.netbsd.org/examples/proplib/ (2016-02-01)
    Open archived version from archive

  • socket programming
    ANY ADDRESS Let s have a closer look about the above lines This line make memset for ServAddr structure This structure holds the server address and all information needed about the socket work memset ServAddr 0 sizeof ServAddr This line put the socket family So as i said above the socket can be internet and local It this example it is internet because of that we put AF INET ServAddr sin family AF INET The following line specifies that we accept connections from ANY address ServAddr sin addr s addr htonl INADDR ANY s addr is variable that holds the information about the address we agree to accept So in this case i put INADDR ANY because i would like to accept connections from any internet address This case is used about server example In a client example i could NOT accept connections from ANY ADDRESS After all above stuffs the next important thing is the PORT all internet sockets need a Input Output PORT to make a connection You can take any port that you want the required condition is that port to be free So in other words it must be available for us NOTE Some ports need ROOT rights to opened If this port is compromised it put entire Operating System on risk So i suggest using a NONE ROOT PORTS that are pretty much available in the computer These ports start from 1500 65536 Well you have all these ports available for ordinary NONE ROOT users Here is the example about the port initializing ServAddr sin port htons port Let me describe the above line So the port is a integer variable You can do it in this way ServAddr sin port htons 10203 This above line will open port 10203 for connections Client Side specific options Connect to the server The client can be connected to the server via connect function That function takes our current socket it is a client in that case and the server socket and connect them both Here is the example code connect sock struct sockaddr ServAddr sizeof ServAddr To be everything good and everybody to be happy do the following code if connect sock struct sockaddr ServAddr sizeof ServAddr 0 printf connect failed n This code make sure that we have available connection If the connection failed then the connect function will return 1 and the logic will print the error message connect failed If the function succeeded there is an available and ready for using connection to the server Server Side specific options Binding the socket After the all preparations the next important step is socket binding This will bind the socket address and the created socket So the address will be connected to the socket If you miss this stuff you can not use your socket Because it will have no address to access it This is like the building and the street number If you don t know street number you could not find the building you want Well here is the example how to do that bind sock struct sockaddr ServAddr sizeof ServAddr The bind function is very important because it will make your socket available for using So better way to do above is to import some processing logic to make sure yourself that is really available socket This will do binding of the socket but will check for errors and if the binding failed the logic will do exit if bind sock struct sockaddr ServAddr sizeof ServAddr 0 perror bind exit EXIT FAILURE Listening for incoming connections listen sock MAXPENDING The second argument specifies the length of the queue for pending connections So if you want to use 5 pending connections you can do it in this way listen sock 5 This marks the socket is listening and ready to accept incoming connections Accepting connections The accepting of the connections goes throw some steps First of all it needs to make a structure with type sockaddr in to hold client address After that have to make a variable to hold the client length Then i put the length of the client to this variable So i make sure that there is enough data Here is the example code struct sockaddr in ClntAddr unsigned int clntLen clntLen sizeof ClntAddr clntSock accept servSock struct sockaddr ClntAddr clntLen Transferring data Sending When the sockets are connected the next step is just using of this connection Sending of data can be established via send or write functions Here is the example send sock n StringLen 0 This is simple example how to send a n character to the server We can send any information Characters symbols any data that have to be sent Let me describe the above example So the first argument take a socket variable The second argument take the data that will be sent and the 3rd argument is an integer variable that will specify how long is the data sent The last argument is for additional options if you don t need that just put 0 like me NOTE The variable sock is a socket that will be used But this is your socket not the socket of the server I think this can confuse someone So i assume your make a network client and for that reason you make a client socket That s good but throw this client socket you do all the communications Have a closer look and see the difference between these 2 sockets You use the client socket not the server one the server socket is for the server Just wanted to be clear because some people make mistake when they make a server and client sides Receiving When some data is sent from the other side someone wait to receive it So this is not so hard Here is a simple example recv sock recvBuffer 256 The receiving is like sending simple and easy The first argument takes a socket variable the second variable takes the BUFFER for storing incoming data and the last one takes the integer variable that specifies the length of the incoming data So when you put 256 the read function will read 256 bytes from the incoming data and it will exit when the data is more or find the symbol END OF DATA IMPORTANT Reserve BUFFER as the same or larger of the length you specify as read data DO NOT specify buffer that is smaller of the read data If you do that you will get SEGMENTATION FAULT error message and YOUR PROGRAM WILL TERMINATE NOTE The variable sock is a socket that will be used But this is your socket not the socket of the server I think this can confuse someone So i assume your make a network client and for that reason you make a client socket That s good but throw this client socket you do all the communications Have a closer look and see the difference between these 2 sockets You use the client socket not the server one the server socket is for the server Just wanted to be clear because some people make mistake when they make a server and client sides Advanced tricks There is a huge amount of advanced tricks in the BSD sockets This is the main tricks Receiving data Data receiving is important part of network socket communications There is a issue with the buffer when you receive some data via network if you receive data shorter than the length of buffer data You will receive some data so this is bad Because of that you have to fix the received buffer and the sent data to be exactly the same length BUT the receiving buffer must larger 1 character than the sent data This is because of the last character 0 for terminating the data So if you send this some data to be send this is 20 length message Then buffer for the receiving MUST BE 20 1 This is because you send 20 characters but you receive 20 1 characters The last one is the terminating character Full example source code network h include netinet in h include netdb h include sys socket h include arpa inet h include stdlib h include stdio h define ADRESS PORT 10203 define ADRESS IP 127 0 0 1 define MAXPENDING 5 define BUFFSIZE 21 define SERVER SOCKET 1 define CLIENT SOCKET 0 define TRUE 1 define FALSE 0 define START 11 define DIVIDER network c include network h int make socket uint16 t port int type const char server IP int sock struct hostent hostinfo NULL struct sockaddr in server address Create the socket sock socket PF INET SOCK STREAM IPPROTO TCP if sock 0 perror socket exit 1 Give the socket a name memset server address 0 sizeof server address server address sin family AF INET server address sin port htons port if type SERVER SOCKET server address sin addr s addr htonl INADDR ANY if bind sock struct sockaddr server address sizeof server address 0 perror bind exit 1 if listen sock MAXPENDING 0 printf listen failed else if type CLIENT SOCKET server address sin addr s addr inet addr server IP Establish the connection to the server if connect sock struct sockaddr server address sizeof server address 0 printf connect failed n return sock void close socket int socket close socket char clean data const char data int count char ptr data NULL char result data NULL char temp ptr data NULL int len int write info ifone ptr data strstr data DIVIDER ptr data ptr data strlen DIVIDER temp ptr data malloc strlen ptr data strcpy temp ptr data ptr data result data char strsep temp ptr data DIVIDER printf i i s strlen data strlen ptr data result data return result data void send data int socket const char data int sent bytes all sent bytes int err status int sendstrlen sendstrlen strlen data all sent bytes 0 sent bytes send socket data sendstrlen 0 all sent bytes all sent bytes sent bytes printf t Sent data s n data server c include network h int accept connection int server socket int client socket Socket descriptor for client struct sockaddr in client address Client address unsigned int client length Length of client address data structure Set the size of the in out parameter client length sizeof client address Wait for a client to connect if client socket accept server socket struct sockaddr client address client length 0 printf accept failed client socket is connected to a client printf Handling client s n inet ntoa client address sin addr return client socket void handle client int client socket char buffer BUFFSIZE Buffer for incomming data int msg size Size of received message int bytes all bytes do alarm 60 msg size read client socket buffer BUFFSIZE alarm 0 if msg size 0 printf i msg size printf End of data n while msg size 0 printf Data received s buffer bytes 0 int main int clnt sock int sock make socket ADRESS PORT SERVER SOCKET none clnt sock accept connection sock handle client clnt sock close socket sock return 0 client c include network h int main int sock make socket ADRESS PORT CLIENT SOCKET 10 35 43 41 send data sock Some data to be sent close socket sock return 0 How to compile it Compile via cc cc network c server c o server example server cc network c client c o client example client To compile and use the sockets just have to include the main include files If you don t know which are they here you are Just import these lines in the beginning of your program h files include netinet in h include netdb h include sys socket h include arpa inet h include stdlib h include stdio h Include these and should have no problems Description BSD sockets are the base part of the networks and internet The entire HOW TO is specified about the BSD socket programming but it could be used by other programmers too Well the sockets are the same in all operating systems In the general case this HOW TO will describe about Sockets programming in all NIX like operating systems This include GNU Linux BSD OpenSolaris and others RSS Atom Using NetBSD based sockets implement a TCP client and TCP Server to demonstrate trivially secure file download from server Using NetBSD based sockets implement a TCP client and TCP Server to demonstrate trivially secure file download from server Environment Tools required Linux RHEL4 5 6 and gcc g compiler and vi editor recommended OR Windows XP Vista 7 8 with Visual studio Learning Objective for student Understand Protocol messaging and parsing Manage multiple connections at a server side Manage the state of a connection at both client and server side Ability to use NetBSD Sockets via C API Binary vs Text and practical issues with Endianness Ability to effectively use fread fwrite APIs for file management can also use read write system calls Understanding Standards and compatibility and the inherent difficulty between different not differing implementations Note This is a group assignment Each group can have maximum of 10 students If group of 10 students is opted 5 students may contribute to the client and another 5 students may contribute to the server but put together at a minimum the expected result is a group s server should work with its own client If a group s server client are compatible with other group s client servers it will receive more credit Each group is expected to write both the client and a server 1 Details The messaging mechanism is based on Type Length Value TLV The Message Format is TYPE Field Length Field Value field 8 bytes 4 Bytes int buffer of length bytes Note If Length Field is ZERO then the Value field is empty which is still a perfectly valid message eg LOGINOK message See details below All types are of size 8 chars and always uppercase Valid Types for Client messages are LOGIN AUTH GETFILE Valid Types for Server messages are NEEDAUTH LOGINOK DATA ERROR As Type field is 8 bytes it will employ SPACE as padding i e LOGIN will be sent as LOGIN The message exchange details are as below Client connects to the server LOGIN is the first message sent by the client If server requires authentication it replies with NEEDAUTH message If server does not require authentication it replies with LOGINOK message Client sends back AUTH message as a reply to NEEDAUTH message Server replies with LOGINOK if authentication successful else replies will reply with ERROR and close the connection Client if login was ok i e received LOGINOK message can send at any time a file download request by sending the message GETFILE Note Only outgoing request must be in the network pipe Upon receiving a GETFILE message if server finds a matching file it can send the file contents back in the DATA message If no matching file it may send back an ERROR message Note any time the client can close the connection and go away server needs to detect this and close the connection on its side as well eg if while server is sending a file the client goes away server needs to stop then and there 2 The Client upon receiving the DATA message should store the contents appropriately into a file for later viewing Server never advertises the file list on the server unlike SCP SFTP FTP so clients need to know the file names a simple way is to query the user Note A fancy UI is not required rather a basic working UI with scanf or fgets should suffice Note about GETFILE The GETFILE message can send as value a full path name absolute or a relative path name with as directory separator eg If hello details txt is sent server is supposed to look in its working directory the given path of the file So in this case hello details txt and details txt may refer to completely different files Command Line arguments TSServer TSClient Note about Auth Mechanism Any 2 way auth mechanism can be employed trivially a Salted Password hash based mechanism can be employed This avoids replay attacks NOTE If the environment chosen is Linux it comes with a tool called md5sum which can be used to generate the Hashes on both client side and server side The server can store the list of passwords in some file Bad Not secure but ok for this barebones version Both the server and client programs may run in the same machine during development but for testing it would be ideal to run them in different machines to see how a client server reacts when network goes away Intentionally pull out the ethernet cable when the client is downloading a big file 3 Message Details There are totally 7 messages Syntax Structure is as below 1 LOGIN 2 NEEDAUTH randomly generated 3 AUTH 4 LOGINOK no value sent O byte length 5 ERROR can be 0 byte length or contain an error string 6 GETFILE 7 DATA x bytes indicating size x bytes of data Note x can be 0 which means empty file A Sample Messaging C Client S Server C LOGIN rajesh S NEEDAUTH aa1123 C AUTH Hash Password aa1123 S LOGINOK C GETFILE detail txt S ERROR No Such file C GETFILE details txt S DATA 100 some data of 100 bytes Client closes the connection after receiving the DATA and stores the data received into a file Extras Optional Attempting will lead to Extra credit Server side 1 Server can timeout an idle connection where the idle timeout can be set as a command line argument 2 Server can close the connection if client sends x number of bad GETFILE messages x can be made configurable 3 Server side handling of

    Original URL path: http://wiki.netbsd.org/examples/socket_programming/ (2016-02-01)
    Open archived version from archive

  • audio-hardware
    Query bug database Security Community Blogs Mailing lists List archives Developers Browse source Cross reference Release engineering Projects list Ports History Emulators Packages Browse packages Release engineering Wiki Home Edit Comment Source History New RecentChanges NetBSD Wiki features audio hardware Supported Audio hardware Audio devices are supported by the audio 4 and mixer 4 drivers Release Platform Audio hardware 3 i386 amd64 Intel 82801GB GR azalia Realtek ALC882 codec 3

    Original URL path: http://wiki.netbsd.org/features/audio-hardware/ (2016-02-01)
    Open archived version from archive