IPv6 Network Programming This page intentionally left blank IPv6 Network Programming Jun-ichiro itojun Hagino Amsterdam • Boston (cid:127) Heidelberg (cid:127) London (cid:127) New York (cid:127) Oxford Paris (cid:127) San Diego (cid:127) San Francisco (cid:127) Singapore (cid:127) Sydney (cid:127) Tokyo ElsevierDigitalPress 30CorporateDrive,Suite400,Burlington,MA01803,USA LinacreHouse,JordanHill,OxfordOX28DP,UK Copyright©2004,ElsevierInc. Allrightsreserved. Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,ortransmittedin anyformorbyanymeans,electronic,mechanical,photocopying,recording,orotherwise, withoutthepriorwrittenpermissionofthepublisher. PermissionsmaybesoughtdirectlyfromElsevier’sScience&TechnologyRights DepartmentinOxford,UK:phone:(+44)1865843830,fax:(+44)1865853333,e-mail: [email protected]. Youmayalsocompleteyourrequeston-lineviatheElsevier homepage(http://elsevier.com),byselecting “CustomerSupport”andthen“Obtaining Permissions.” Recognizingtheimportanceofpreservingwhathasbeenwritten,Elsevierprintsitsbookson acid-freepaperwheneverpossible. LibraryofCongressCataloging-in-PublicationData BritishLibraryCataloguing-in-PublicationData AcataloguerecordforthisbookisavailablefromtheBritishLibrary. ISBN: 1-55558-318-0 ForinformationonallElsevierDigitalPresspublicationsvisitourWebsiteat www.books.elsevier.com 04 05 06 07 08 09 10 9 8 7 6 5 4 3 2 1 PrintedintheUnitedStatesofAmerica Contents Preface vii About This Book ix Write Portable Application Programs ix Be Security Conscious When Writing Programs ix Terminology and Portability x 1 Introduction 1 1.1 A History of IPv6 and Its Key Features 1 1.2 Transition from IPv4-Only Internet to IPv4/v6 Dual Stack Internet 4 1.3 UNIX Socket Programming 6 1.4 IPv6 Architecture from a Programmer’s Point of View 10 2 IPv6 Socket Programming 13 2.1 AF_INET6: The Address Family for IPv6 13 2.2 Why Programs Need to Be Address-Family Independent? 14 2.3 Guidelines to Address-Family Independent Socket Programming 17 3 Porting Applications to Support IPv6 27 3.1 Making Existing Applications IPv6 Ready 27 3.2 Finding Where to Rewrite, Reorganizing Code 27 3.3 Rewriting Client Applications 29 3.4 Rewriting Server Applications 31 v vi Contents 4 Tips in IPv6 Programming 49 4.1 Parsing a IPv6 Address out of String 49 4.2 Issues with “:” As a Separator 49 4.3 Issues with an IPv4 Mapped Address 50 4.4 bind(2) Ordering and Conflicts 51 4.5 How IPv4 Traffic Gets Routed to Sockets 52 4.6 Portability across Systems 52 4.7 RFCs 2292/3542, Advanced API 54 4.8 Platform Support Status 54 5 A Practical Example 59 5.1 Server Program Example—popa3d 59 5.2 Further Extensions 62 5.3 Client Program Example—nail 62 A Coming updates to IPv6 APIs 81 B RFC2553 “Basic Socket Interface Extensions for IPv6" 83 C RFC3493 “Basic Socket Interface Extensions for IPv6” 125 D RFC2292 “Advanced Sockets API for IPv6" 165 E RFC3542 “Advanced Sockets Application Program Interface (API) for IPv6" 233 F IPv4-Mapped Address API Considered Harmful 311 G IPv4-Mapped Addresses on the Wire Considered Harmful 317 H Possible Abuse Against IPv6 Transition Technologies 323 I An Extension of format for IPv6 Scoped Addresses 333 J Protocol Independence Using the Sockets API 345 References 355 Preface HereinJapan,itlooksliketheInternetisdeployedeverywhere.Notadaywillgoby without hearing the word Internet. However, many people do not know that we are very close to reaching the theoretical limit of IPv4. The theoretical limit for the numberofIPv4nodesisonly4billion—muchfewerthantheworld’spopulation. Peopleintrains andcarssendemailontheircellphonesusingsmallnumerickey- pads.MostofthesedevicesarenotconnectedtotherealInternet—thesecellphonesdo notspeaktheInternetProtocol.Theyuseproprietaryprotocolstodeliveremailstothe gateway,andthegatewayrelaystheemailstotheInternet.Cellularoperatorsarenow tryingtomakecellphonesarealVoIPdevice(insteadof“emailonly”device)toavoid thecostsofoperatingproprietaryphoneswitches/devices/gatewaysandtouseinexpen- siveIProuters. There are a lot of areas where the Internet and the Internet Protocol have to be deployed. For instance, we need to enable every vehicle to be connected to the IP networkinordertoexchangeinformationabouttrafficcongestion.Thereareplansto interconnecteveryconsumerdevicetotheInternet,sothatvendorscancollectinfor- mation from the machines (such as statistics), as well as provide various value-added services. Also,weneedtodeployIPtoeverycountryintheworld,includinghighlypopu- latedareassuchasChina,India,andAfrica,sothateveryonehasequalopportunityto accesstheinformationontheInternet. To deploy the Internet Protocol to wider domains, the transition from IPv4 to IPv6iscritical.IPv4cannotaccommodatetheneedsdiscussedpreviously,duetothe limitation in address space size. With IPv6 we will be able to accomodate 3.4× 1038 nodestotheInternet—itshouldbeenoughforourlifetime(Ihope). vii viii Preface The IPv6 effort was started in 1992, in the INET92 conference held in Kobe, Japan.Sincethen,wehavebeenmakingahugeamountofefforttohelpthetransition happen. Fortunately, it seems that the interest in IPv6 has reached the critical mass, andthetransitiontoIPv6isnowareality.ManyISPsinJapanareofferingcommercial IPv6 connectivity services, numerous vendors are shipping IPv6-enabled operating systems, and many IPv6-enabled products are coming. If you are not ready yet, you needtohurryup. ThetransitiontoIPv6requiresanupgradeofroutersoftwareandhostoperating systems, as well as application software. This book focuses on how you can modify your network application software, based on the socket API, to support IPv6. When you write a network application program, you will want the program to be IPv6- capable,sothatitwillworkjustfineontheIPv6network,aswellastheIPv4network. Aftergoingthroughthisbook,youwillbeabletomakeyourprogramsIPv6-ready.It will also help you port your IPv4-capable application to become IPv6-capable at the sametime. Inthisbook,weadvocateaddress-familyindependentsocketlayerprogramming forIPv6transition.Byfollowingtheinstructionsinthebook,yourcodewillbecome independentfromtheaddressfamily(suchasAF_INETorAF_INET6).Thisisthe bestwaytosupportIPv6inyourprogram,comparedwithotherapproaches(suchas hardcodingAF_INET6intotheprogram). I would like to thank the editor for the Japanese edition of the book, Ms. Eiko Akashima,andtranslatorfortheJapaneseeditionofthebook,Ms.AyakoOgawa(the original manuscript of the book is in English, even though it was first published inJapan).Onthetechnicalside,IwouldliketothankMr.CraigMetz,whogenerously permittedustoincludehispaperonaddress-familyindependentprogramming,aswell asthemembersoftheWIDE/KAMEproject,whohavemadealotofusefulsugges- tionstothecontentofthebook. Jun-ichiroitojunHagino Tokyo,Japan About This Book ThisbooktriestooutlinehowtowriteanIPv6-capableapplicationonaUNIXsocket API, or how to update your IPv4 application to be IPv6-capable. The book tries to showportableandsecurewaystoachievethesegoals. Write Portable Application Programs TherearealargenumberofplatformsthatsupportsocketAPIfornetworkprogram- ming.WhenyouwriteanapplicationontopofsocketAPI,youwillwanttoseeyour programworkonasmanyplatformsaspossible.Therefore,portabilityisanimportant factor in application programming. As many of you already know, there are many UNIX-likeoperatingsystems,aswellasnon-UNIXoperatingsystemsthatimplement socketAPIs.Forinstance,WindowsXPdoesimplementsocketAPI;MacOSXuses BSDUNIXasthebaseoperatingsystemandprovidessocketAPItotheusers(Apple normallyrecommendstheuseofAppleAPIs).Sothebooktriestorecommendport- ablewaysofwritingIPv6-capableprograms. Be Security Conscious When Writing Programs SecurityisagreatconcernthesedaysintheInternet—ifyouareanetworkadministra- tor,Iguessyouarereceivingtonsofspam,emailviruses,andvendoradvisoriesevery day. To secure the Internet infrastructure, every developer has to take a security stance—toauditeverylineofcodeasmuchaspossible,touseproperAPI,andwritea correctandsecurecode.Toachievethisgoal,inthisbook,effortsaremadetoensure correctness of the examples. The examples presented in this book are implemented with security stance. Also, the book tries to lead you to write secure programs. For instance, the book recommends against the use of some of the IPv6 standard APIs; ix