Você está na página 1de 14

30/08/2016

networking - How does IPv4 Subnetting Work? - Server Fault

ServerFaultisaquestionandanswer
siteforsystemandnetwork
administrators.Jointhemitonlytakesa
minute:
Signup

signup

login

tour

Here'showitworks:

Anybodycanask
aquestion

help

Anybodycan
answer

Thebestanswersarevoted
upandrisetothetop

HowdoesIPv4SubnettingWork?
ThisisaCanonicalQuestionaboutIPv4Subnets.
Related:
HowdoesIPv6subnettingworkandhowdoesitdifferfromIPv4subnetting?
HowdoesSubnettingWork,andHowdoyoudoitbyhandorinyourhead?Cansomeoneexplainbothconceptuallyandwithseveral
examples?ServerFaultgetslotsofsubnettinghomeworkquestions,sowecoulduseananswertopointthemtoonServerFaultitself.
Whatisclasslessroutingandwhyisclassbasedroutingobsolete?
IfIhaveanetwork,howdoIfigureouthowtosplititup?
IfIamgivenanetmask,howdoIknowwhatthenetworkRangeisforit?
Sometimesthereisaslashfollowedbyanumber,whatisthatnumber?
Sometimesthereisasubnetmask,butalsoawildcardmask,theyseemlikethesamethingbuttheyaredifferent?
Someonementionedsomethingaboutknowingbinaryforthis?
WhatisNAT(NetworkAddressTranslation).
networking subnet tcpip
editedSep11'12at3:08

communitywiki
17revs,9users41%
KyleBrandt

6Answers

IPsubnetsexisttoallowrouterstochooseappropriatedestinationsforpackets.Youcanuse
IPsubnetstobreakuplargernetworksforlogicalreasons(firewalling,etc),orphysicalneed
(smallerbroadcastdomains,etc).
Simplyput,though,IProutersuseyourIPsubnetstomakeroutingdecisions.Understandhow
thosedecisionswork,andyoucanunderstandhowtoplanIPsubnets.

Countingto1
Ifyouarealreadyfluentinbinary(base2)notationyoucanskipthissection.
Forthoseofyouwhoareleft:Shameonyoufornotbeingfluentinbinarynotation!
Yeahthatmaybeabitharsh.It'sreally,reallyeasytolearntocountinbinary,andtolearn
shortcutstoconvertbinarytodecimalandback.Youreallyshouldknowhowtodoit.
Countinginbinaryissosimplebecauseyouonlyhavetoknowhowtocountto1!
Thinkofacar's"odometer",exceptthatunlikeatraditionalodometereachdigitcanonlycount
upto1from0.Whenthecarisfreshfromthefactorytheodometerreads"00000000".
Whenyou'vedrivenyourfirstmiletheodometerreads"00000001".Sofar,sogood.
Whenyou'vedrivenyoursecondmilethefirstdigitoftheodometerrollsbackoverto"0"(since
it'smaximumvalueis"1")andtheseconddigitoftheodometerrollsoverto"1",makingthe
odometerread"00000010".Thislookslikethenumber10indecimalnotation,butit'sactually
2(thenumberofmilesyou'vedriventhecarsofar)inbinarynotation.
Whenyou'vedriventhethirdmiletheodometerreads"00000011",sincethefirstdigitofthe
odometerturnsagain.Thenumber"11",inbinarynotation,isthesameasthedecimalnumber
3.
Finally,whenyou'vedrivenyourfourthmilebothdigits(whichwerereading"1"attheendof
thethirdmile)rollbackovertozeroposition,andthe3rddigitrollsuptothe"1"position,giving
us"00000100".That'sthebinaryrepresentationofthedecimalnumber4.
Youcanmemorizeallofthatifyouwant,butyoureallyonlyneedtounderstandhowthelittle

http://serverfault.com/questions/49765/how-does-ipv4-subnetting-work/49836#49836

1/14

30/08/2016

networking - How does IPv4 Subnetting Work? - Server Fault

odometer"rollsover"asthenumberit'scountinggetsbigger.It'sexactlythesameasa
traditionaldecimalodometer'soperation,exceptthateachdigitcanonlybe"0"or"1"onour
fictional"binaryodometer".
Toconvertadecimalnumbertobinaryyoucouldrolltheodometerforward,tickbytick,
countingalouduntilyou'verolleditanumberoftimesequaltothedecimalnumberyouwantto
converttobinary.Whateverisdisplayedontheodometerafterallthatcoutingandrolling
wouldbethebinaryrepresentationofthedecimalnumberyoucountedupto.
Sinceyouunderstandhowtheodometerrollsforwardyou'llalsounderstandhowitrolls
backward,too.Toconvertabinarynumberdisplayedontheodometerbacktodecimalyou
couldrolltheodometerbackonetickatatime,countingalouduntiltheodometerreads
"00000000".Whenallthatcountingandrollingisdone,thelastnumberyousayaloudwould
bethedecimalrepresentationofthebinarynumbertheodometerstartedwith.
Convertingvaluesbetweenbinaryanddecimalthiswaywouldbeverytedious.Youcoulddoit,
butitwouldn'tbeveryefficient.It'seasiertolearnalittlealgorithmtodoitfaster.
Aquickaside:Eachdigitinabinarynumberisknownasa"bit".That's"b"from"binary"and
"it"from"digit".Abitisabinarydigit.
Convertingabinarynumberlike,say,"1101011"todecimalisasimpleprocesswithahandy
littlealgorithm.
Startbycountingthenumberofbitsinthebinarynumber.Inthiscase,thereare7.Make7
divisionsonasheetofpaper(inyourmind,inatextfile,etc)andbeginfillingtheminfromright
toleft.Intherightmostslot,enterthenumber"1",becausewe'llalwaysstartwith"1".Inthe
nextslottotheleftenterdoublethevalueintheslottotheright(so,"2"inthenextone,"4"in
thenextone)andcontinueuntilalltheslotsarefull.(You'llendupmemorizingthesenumbers,
whicharethepowersof2,asyoudothismoreandmore.I'malrightupto131,072inmyhead
butIusuallyneedacalculatororpaperafterthat).
So,youshouldhavethefollowingonyourpaperinyourlittleslots.
64|32|16|8|4|2|1|

Transcribethebitsfromthebinarynumberbelowtheslots,likeso:
64|32|16|8|4|2|1|
1101011

Now,addsomesymbolsandcomputetheanswertotheproblem:
64|32|16|8|4|2|1|
x1x1x0x1x0x1x1

++++++=

Doingallthemath,youshouldcomeupwith:
64|32|16|8|4|2|1|
x1x1x0x1x0x1x1

64+32+0+8+0+2+1=107

That'sgotit."1101011"indecimalis107.It'sjustsimplestepsandeasymath.
Convertingdecimaltobinaryisjustaseasyandisthesamebasicalgorithm,runinreverse.
Saythatwewanttoconvertthenumber218tobinary.Startingontherightofasheetofpaper,
writethenumber"1".Totheleft,doublethatvalue(so,"2")andcontinuemovingtowardtheleft
ofthepaperdoublingthelastvalue.Ifthenumberyouareabouttowriteisgreaterthanthe
numberbeingconvertedstopwriting.otherwise,continuedoublingthepriornumberand
writing.(Convertingabignumber,like34,157,216,092,tobinaryusingthisalgorithmcanbea
bittediousbutit'scertainlypossible.)
So,youshouldhaveonyourpaper:
128|64|32|16|8|4|2|1|

Youstoppedwritingnumbersat128becausedoubling128,whichwouldgiveyou256,would
belargethanthenumberbeingconverted(218).
Beginningfromtheleftmostnumber,write"218"aboveit(128)andaskyourself:"Is218larger
thanorequalto128?"Iftheanswerisyes,scratcha"1"below"128".Above"64",writethe
resultof218minus128(90).
Lookingat"64",askyourself:"Is90largerthanorequalto64?"Itis,soyou'dwritea"1"below
"64",thensubtract64from90andwritethatabove"32"(26).
Whenyougetto"32",though,youfindthat32isnotgreaterthanorequalto26.Inthiscase,
writea"0"below"32",copythenumber(26)fromabove32"toabove"16"andthencontinue
askingyourselfthesamequestionwiththerestofthenumbers.
Whenyou'realldone,youshouldhave:
21890262610220
128|64|32|16|8|4|2|1|

http://serverfault.com/questions/49765/how-does-ipv4-subnetting-work/49836#49836

2/14

30/08/2016

networking - How does IPv4 Subnetting Work? - Server Fault

11011010

Thenumbersatthetoparejustnotesusedincomputationanddon'tmeanmuchtous.Atthe
bottom,though,youseeabinarynumber"11011010".Sureenough,218,convertedtobinary,
is"11011010".
Followingtheseverysimpleproceduresyoucanconvertbinarytodecimalandbackagainw/o
acalculator.Themathisallverysimpleandtherulescanbememorizedwithjustabitof
practice.

SplittingUpAddresses
ThinkofIProutinglikepizzadelivery.
Whenyou'reaskedtodeliverapizzato"123MainStreet"it'sverycleartoyou,asahuman,
thatyouwanttogotothebuildingnumbered"123"onthestreetnamed"MainStreet".It'seasy
toknowthatyouneedtogotothe100blockofMainStreetbecausethebuildingnumberis
between100and199andmostcityblocksarenumberedinhundreds.You"justknow"howto
splittheaddressup.
Routersdeliverpackets,notpizza.Theirjobisthesameasapizzadriver:Togetthecargo
(packets)asclosetothedestinationaspossible.ArouterisconnectedtotwoormoreIP
subnets(tobeatalluseful).AroutermustexaminedestinationIPaddressesofpacketsand
breakthosedestinationaddressesupintotheir"streetname"and"buildingnumber"
components,justlikethepizzadriver,tomakedecisionsaboutdelivery.
Eachcomputer(or"host")onanIPnetworkisconfiguredwithauniqueIPaddressandsubnet
mask.ThatIPaddresscanbedividedupintoa"buildingnumber"component(like"123"inthe
exampleabove)calledthe"hostID"anda"streetname"component(like"MainStreet"inthe
exampleabove)calledthe"networkID".Forourhumaneyes,it'seasytoseewherethe
buildingnumberandthestreetnamearein"123MainStreet",buthardertoseethatdivisionin
"10.13.216.41withasubnetmaskof255.255.192.0".
IProuters"justknow"howtosplitupIPaddressesintothesecomponentpartstomakerouting
decisions.SinceunderstandinghowIPpacketsareroutedhingesonunderstandingthis
processweneedtoknowhowtobreakupIPaddresses,too.Fortunately,extractingthehost
IDandthenetworkIDoutofanIPaddressandsubnetmaskisactuallyprettyeasy.
StartbywritingouttheIPaddressinbinary(useacalculatorifyouhaven'tlearnedtodothisin
yourheadjustyet,butmakeanotelearnhowtodoitit'sreally,reallyeasyandimpresses
theoppositesexatparties):
10.13.216.41
00001010.00001101.11011000.00101001

Writeoutthesubnetmaskinbinary,too:
255.255.192.0
11111111.11111111.11000000.00000000

Writtensidebyside,youcanseethatthepointinthesubnetmaskwherethe"1's"stop"lines
up"toapointintheIPaddress.That'sthepointthatthenetworkIDandthehostIDsplit.So,in
thiscase:
10.13.216.41
00001010.00001101.11011000.00101001IPaddress
11111111.11111111.11000000.00000000subnetmask
00001010.00001101.11000000.00000000PortionofIPaddresscoveredby1'sin
subnetmask,remainingbitssetto0
00000000.00000000.00011000.00101001PortionofIPaddresscoveredby0'sin
subnetmask,remainingbitssetto0

Routersusethesubnetmaskto"maskout"thebitscoveredby1'sintheIPaddress(replacing
thebitsthatarenot"maskedout"with0's)toextractthenetworkID:
10.13.192.0
00001010.00001101.11000000.00000000NetworkID

Likewise,byusingthesubnetmaskto"maskout"thebitscoveredby0'sintheIPaddress
(replacingthebitsthatarenot"maskedout"with0'sagain)aroutercanextractthehostID:
0.0.24.41
00000000.00000000.00011000.00101001PortionofIPaddresscoveredby0'sin
subnetmask,remainingbitssetto0

It'snotaseasyforourhumaneyestoseethe"break"betweenthenetworkIDandthehostID
asitisbetweenthe"buildingnumber"andthe"streetname"inphysicaladdressesduring
pizzadelivery,buttheultimateeffectisthesame.
NowthatyoucansplitupIPaddressesandsubnetmasksintohostID'sandnetworkID'syou
canrouteIPjustlikearouterdoes.

MoreTerminology
You'regoingtoseesubnetmaskswrittenallovertheInternetandthroughouttherestofthis
answeras(IP/number).Thisnotationisknownas"ClasslessInterDomainRouting"(CIDR)
notation."255.255.255.0"ismadeupof24bitsof1'satthebeginning,andit'sfastertowrite

http://serverfault.com/questions/49765/how-does-ipv4-subnetting-work/49836#49836

3/14

30/08/2016

networking - How does IPv4 Subnetting Work? - Server Fault

thatas"/24"thanas"255.255.255.0".ToconvertaCIDRnumber(like"/16")toadotted
decimalsubnetmaskjustwriteoutthatnumberof1's,splititintogroupsof8bits,andconvert
ittodecimal.(A"/16"is"255.255.0.0",forinstance.)
Backinthe"olddays",subnetmasksweren'tspecified,butratherwerederivedbylookingat
certainbitsoftheIPaddress.AnIPaddressstartingwith0127,forexample,hadanimplied
subnetmaskof255.0.0.0(calleda"classA"IPaddress).
Theseimpliedsubnetmasksaren'tusedtodayandIdon'trecommendlearningaboutthem
anymoreunlessyouhavethemisfortuneofdealingwithveryoldequipmentoroldprotocols
(likeRIPv1)thatdon'tsupportclasslessIPaddressing.I'mnotgoingtomentionthese
"classes"ofaddressesfurtherbecauseit'sinapplicabletodayandcanbeconfusing.
Somedevicesuseanotationcalled"wildcardmasks".A"wildcardmask"isnothingmorethan
asubnetmaskwithall0'swheretherewouldbe1's,and1'swheretherewouldbe0's.The
"wildcardmask"ofa/26is:
11111111.11111111.11111111.11000000/26subnetmask
00000000.00000000.00000000.00111111/26"wildcardmask"

Typicallyyousee"wildcardmasks"usedtomatchhostIDsinaccesscontrollistsorfirewall
rules.Wewon'tdiscussthemanyfurtherhere.

HowaRouterWorks
AsI'vesaidbefore,IProutershaveasimilarjobtoapizzadeliverydriverinthattheyneedto
gettheircargo(packets)toitsdestination.Whenpresentedwithapacketboundforaddress
192.168.10.2,anIProuterneedstodeterminewhichofitsnetworkinterfaceswillbestgetthat
packetclosertoitsdestination.
Let'ssaythatyouareanIProuter,andyouhaveinterfacesconnectedtoyounumbered:
Ethernet0192.168.20.1,subnetmask/24
Ethernet1192.168.10.1,subnetmask/24
Ifyoureceiveapackettodeliverwithadestinationaddressof"192.168.10.2",it'sprettyeasy
totell(withyourhumaneyes)thatthepacketshouldbesentouttheinterfaceEthernet1,
becausetheEthernet1interfaceaddresscorrespondstothepacket'sdestinationaddress.All
thecomputersattachedtotheEthernet1interfacewillhaveIPaddressesstartingwith
"192.168.10.",becausethenetworkIDoftheIPaddressassignedtoyourinterfaceEthernet1
is"192.168.10.0".
Forarouter,thisrouteselectionprocessisdonebybuildingaroutingtableandconsultingthe
tableeachtimeapacketistobedelivered.AroutingtablecontainsnetworkIDanddestination
interfacenames.YoualreadyknowhowtoobtainanetworkIDfromanIPaddressandsubnet
mask,soyou'reonyourwaytobuildingaroutingtable.Here'sourroutingtableforthisrouter:
NetworkID:192.168.20.0(11000000.10101000.00010100.00000000)24bitsubnet
maskInterfaceEthernet0
NetworkID:192.168.10.0(11000000.10101000.00001010.00000000)24bitsubnet
maskInterfaceEthernet1
Forourincomingpacketboundfor"192.168.10.2",weneedonlyconvertthatpacket'saddress
tobinary(ashumanstheroutergetsitasbinaryoffthewiretobeginwith)andattemptto
matchittoeachaddressinourroutingtable(uptothenumberofbitsinthesubnetmask)until
wematchanentry.
Incomingpacketdestination:11000000.10101000.00001010.00000010
Comparingthattotheentriesinourroutingtable:
11000000.10101000.00001010.00000010Destinationaddressforpacket
11000000.10101000.00010100.00000000InterfaceEthernet0
!!!!!!!!.!!!!!!!!.!!!????!.xxxxxxxx!indicatesmatcheddigits,?indicatesno
match,xindicatesnotchecked(beyondsubnetmask)
11000000.10101000.00001010.00000010Destinationaddressforpacket
11000000.10101000.00001010.00000000InterfaceEthernet1,24bitsubnetmask
!!!!!!!!.!!!!!!!!.!!!!!!!!.xxxxxxxx!indicatesmatcheddigits,?indicatesno
match,xindicatesnotchecked(beyondsubnetmask)

TheentryforEthernet0matchesthefirst19bitsfine,butthenstopsmatching.Thatmeansit's
nottheproperdestinationinterface.YoucanseethattheinterfaceEthernet1matches24bits
ofthedestinationaddress.Ah,ha!ThepacketisboundforinterfaceEthernet1.
Inarealliferouter,theroutingtableissortedinsuchamannerthatthelongestsubnetmasks
arecheckedformatchesfirst(i.e.themostspecificroutes),andnumericallysothatassoonas
amatchisfoundthepacketcanberoutedandnofurthermatchingattemptsarenecessary
(meaningthat192.168.10.0wouldbelistedfirstand192.168.20.0wouldneverhavebeen
checked).Here,we'resimplifyingthatabit.Fancydatastructuresandalgorithmsmakefaster
IProuters,butsimplealgorithmswillproducethesameresults.

StaticRoutes
Uptothispoint,we'vetalkedaboutourhypotheticalrouterashavingnetworksdirectly
connectedtoit.That'snot,obviously,howtheworldreallyworks.Inthepizzadrivinganalogy,

http://serverfault.com/questions/49765/how-does-ipv4-subnetting-work/49836#49836

4/14

30/08/2016

networking - How does IPv4 Subnetting Work? - Server Fault

sometimesthedriverisn'tallowedanyfurtherintothebuildingthanthefrontdesk,andhasto
handoffthepizzatosomebodyelsefordeliverytothefinalrecipient(suspendyourdisbelief
andbearwithmewhileIstretchmyanalogy,please).
Let'sstartbycallingourrouterfromtheearlierexamples"RouterA".Youalreadyknow
RouterA'sroutingtableas:
NetworkID:192.168.20.0(11000000.10101000.00010100.00000000)subnetmask/24
InterfaceRouterAEthernet0
NetworkID:192.168.10.0(11000000.10101000.00001010.00000000)subnetmask/24
InterfaceRouterAEthernet1
Supposethatthere'sanotherrouter,"RouterB",withtheIPaddresses192.168.10.254/24and
192.168.30.1/24assignedtoitsEthernet0andEthernet1interfaces.Ithasthefollowingrouting
table:
NetworkID:192.168.10.0(11000000.10101000.00001010.00000000)subnetmask/24
InterfaceRouterBEthernet0
NetworkID:192.168.30.0(11000000.10101000.00011110.00000000)subnetmask/24
InterfaceRouterBEthernet1
InprettyASCIIart,thenetworklookslikethis:
InterfaceInterface
Ethernet1Ethernet1
192.168.10.1/24192.168.30.254/24
__________V__________V
||V||V
|ROUTERA|///|ROUTERB|
^|__________|^|__________|
^^
InterfaceInterface
Ethernet0Ethernet0
192.168.20.1/24192.168.10.254/24

YoucanseethatRouterBknowshowto"getto"anetwork,192.168.30.0/24,thatRouterA
knowsnothingabout.
SupposethataPCwiththeIPaddress192.168.20.13attachedtothenetworkconnectedto
routerA'sEthernet0interfacesendsapackettoRouterAfordelivery.Ourhypotheticalpacket
isdestinedfortheIPaddress192.168.30.46,whichisadeviceattachedtothenetwork
connectedtotheEthernet1interfaceofRouterB.
Withtheroutingtableshownabove,neitherentryinRouterA'sroutingtablematchesthe
destination192.168.30.46,soRouterAwillreturnthepackettothesendingPCwiththe
message"Destinationnetworkunreachable".
TomakeRouterA"aware"oftheexistenceofthe192.168.30.0/24network,weaddthe
followingentrytotheroutingtableonRouterA:
NetworkID:192.168.30.0(11000000.10101000.00011110.00000000)subnetmask/24
Accessiblevia192.168.10.254
Inthisway,RouterAhasaroutingtableentrythatmatchesthe192.168.30.46destinationof
ourexamplepacket.Thisroutingtableentryeffectivelysays"Ifyougetapacketboundfor
192.168.30.0/24,senditonto192.168.10.254becauseheknowshowtodealwithit."Thisis
theanalogous"handoffthepizzaatthefrontdesk"actionthatImentionedearlierpassing
thepacketontosomebodyelsewhoknowshowtogetitclosertoitsdestination.
Addinganentrytoaroutingtable"byhand"isknownasaddinga"staticroute".
IfRouterBwantstodeliverpacketstothe192.168.20.0subnetmask255.255.255.0network,
itwillneedanentryinitsroutingtable,too:
NetworkID:192.168.20.0(11000000.10101000.00010100.00000000)subnetmask/24
Accessiblevia:192.168.10.1(RouterA'sIPaddressinthe192.168.10.0network)
Thiswouldcreateapathfordeliverybetweenthe192.168.30.0/24networkandthe
192.168.20.0/24networkacrossthe192.168.10.0/24networkbetweentheserouters.
Youalwayswanttobesurethatroutersonbothsidesofsuchan"interstitialnetwork"havea
routingtableentryforthe"farend"network.IfrouterBinourexampledidn'thavearouting
tableentryfor"farend"network192.168.20.0/24attachedtorouterAourhypotheticalpacket
fromthePCat192.168.20.13wouldgettothedestinationdeviceat192.168.30.46,butany
replythat192.168.30.46triedtosendbackwouldbereturnedbyrouterBas"Destination
networkunreachable."Onewaycommunicationisgenerallynotdesirable.Alwaysbesureyou
thinkabouttrafficflowinginbothdirectionswhenyouthinkaboutcommunicationincomputer
networks.
Youcangetalotofmileageoutofstaticroutes.DynamicroutingprotocolslikeEIGRP,RIP,
etc,arereallynothingmorethanawayforrouterstoexchangeroutinginformationbetween
eachotherthatcould,infact,beconfiguredwithstaticroutes.Onelargeadvantagetousing
dynamicroutingprotocolsoverstaticroutes,though,isthatdynamicroutingprotocolscan
dynamicallychangetheroutingtablebasedonnetworkconditions(bandwidthutilization,an
interface"goingdown",etc)and,assuch,usingadynamicroutingprotocolcanresultina
configurationthat"routesaround"failuresorbottlenecksinthenetworkinfrastructure.
(DynamicroutingprotocolsareWAYoutsidethescopeofthisanswer,though.)

http://serverfault.com/questions/49765/how-does-ipv4-subnetting-work/49836#49836

5/14

30/08/2016

networking - How does IPv4 Subnetting Work? - Server Fault

YouCan'tGetThereFromHere
InthecaseofourexampleRouterA,whathappenswhenapacketboundfor"172.16.31.92"
comesin?
LookingattheRouterAroutingtable,neitherdestinationinterfaceorstaticroutematchesthe
first24bitsof172.18.31.92(whichis10101100.00010000.00011111.01011100,BTW).
Aswealreadyknow,RouterAwouldreturnthepackettothesenderviaa"Destinationnetwork
unreachable"message.
Saythatthere'sanotherrouter(RouterC)sittingattheaddress"192.168.20.254".RouterC
hasaconnectiontotheInternet!
InterfaceInterface
Interface
Ethernet1Ethernet1
Ethernet1
192.168.20.254/24192.168.10.1/24
192.168.30.254/24
__________V__________V
__________V
((heapo))||V||V|
|V
((internet))|ROUTERC|///|ROUTERA|///|
ROUTERB|
((w00t!))^|__________|^|__________|^
|__________|
^^^
InterfaceInterface
Interface
Ethernet0Ethernet0
Ethernet0
10.35.1.1/30192.168.20.1/24
192.168.10.254/24

ItwouldbeniceifRouterAcouldroutepacketsthatdonotmatchanylocalinterfaceupto
RouterCsuchthatRouterCcansendthemontotheInternet.Enterthe"defaultgateway"
route.
Addanentryattheendofourroutingtablelikethis:
NetworkID:0.0.0.0(00000000.00000000.00000000.00000000)subnetmask/0
Destinationrouter:192.168.20.254
Whenweattempttomatch"172.16.31.92"toeachentryintheroutingtableweenduphitting
thisnewentry.It'sabitperplexing,atfirst.We'relookingtomatchzerobitsofthedestination
addresswith...wait...what?Matchingzerobits?So,we'renotlookingforamatchatall.This
routingtableentryissaying,basically,"Ifyougethere,ratherthangivingupondelivery,send
thepacketontotherouterat192.168.20.254andlethimhandleit".
192.168.20.254isadestinationweDOknowhowtodeliverapacketto.Whenconfrontedwith
apacketboundforadestinationforwhichwehavenospecificroutingtableentrythis"default
gateway"entrywillalwaysmatch(sinceitmatcheszerobitsofthedestinationaddress)and
givesusa"lastresort"placethatwecansendpacketsfordelivery.You'llsometimeshearthe
defaultgatewaycalledthe"gatewayoflastresort."
Inorderforadefaultgatewayroutetobeeffectiveitmustrefertoarouterthatisreachable
usingtheotherentriesintheroutingtable.Ifyoutriedtospecifyadefaultgatewayof
192.168.50.254inRouterA,forexample,deliverytosuchadefaultgatewaywouldfail.
192.168.50.254isn'tanaddressthatRouterAknowshowtodeliverpacketstousinganyof
theotherroutesinitsroutingtable,sosuchanaddresswouldbeineffectiveasadefault
gateway.Thiscanbestatedconcisely:Thedefaultgatewaymustbesettoanaddressalready
reachablebyusinganotherrouteintheroutingtable.
Realrouterstypicallystorethedefaultgatewayasthelastrouteintheirroutingtablesuchthat
itmatchespacketsafterthey'vefailedtomatchallotherentriesinthetable.

UrbanPlanningandIPRouting
BreakingupaIPsubnetintosmallerIPsubnetsislkeurbanplanning.Inurbanplanning,
zoningisusedtoadapttonaturalfeaturesofthelandscape(rivers,lakes,etc),toinfluence
trafficflowsbetweendifferentpartsofthecity,andtosegregatedifferenttypesoflanduse
(industrial,residential,etc).IPsubnettingisreallymuchthesame.
Therearethreemainreasonswhyyouwouldsubnetanetwork:
Youmaywanttocommunicateacrossdifferentunlikecommunicationmedia.Ifyouhavea
T1WANconnectionbetweentwobuildingsIProuterscouldbeplacedontheendsof
theseconnectionstofacilitatecommunicationacrosstheT1.Thenetworksoneachend
(andpossiblythe"interstitial"networkontheT1itself)wouldbeassignedtouniqueIP
subnetssothattherouterscanmakedecisionsaboutwhichtrafficshouldbesentacross
theT1line.
InanEthernetnetwork,youmightusesubnettingtolimittheamountofbroadcasttrafficin
agivenportionofthenetwork.Applicationlayerprotocolsusethebroadcastcapabilityof
Ethernetforveryusefulpurposes.Asyougetmoreandmorehostspackedintothesame
Ethernetnetwork,though,thepercentageofbroadcasttrafficonthewire(orair,in
wirelessEthernet)canincreasetosuchapointastocreateproblemsfordeliveryofnon

http://serverfault.com/questions/49765/how-does-ipv4-subnetting-work/49836#49836

6/14

30/08/2016

networking - How does IPv4 Subnetting Work? - Server Fault

broadcasttraffic.(Intheoldendays,broadcasttrafficcouldoverwhelmtheCPUofhosts
byforcingthemtoexamineeachbroadcastpacket.That'slesslikelytoday.)Excessive
trafficonswitchedEthernetcanalsocomeinformof"floodingofframestounknown
destinations".ThisconditioniscausedbyanEthernetswitchbeingunabletokeeptrackof
everydestinationonthenetworkandisthereasonwhyswitchedEthernetnetworkscan't
scaletoaninfinitenumberofhosts.Theeffectoffloodingofframestounknown
destinationsissimilartothetheeffectofexcessbroadcasttraffic,forthepurposesof
subnetting.
Youmaywantto"police"thetypesoftrafficflowingbetweendifferentgroupsofhosts.
Perhapsyouhaveprintserverdevicesandyouonlywantauthorizedprintqueuingserver
computerstosendjobstothem.Bylimitingthetrafficallowedtoflowtotheprintserver
devicesubnetuserscan'tconfiguretheirPCstotalkdirectlytotheprintserverdevicesto
bypassprintaccounting.Youmightputtheprintserverdevicesintoasubnetallto
themselvesandcreatearuleintherouterorfirewallattachedtothatsubnettocontrolthe
listofhostspermittedtosendtraffictotheprintserverdevices.(Bothroutersandfirewalls
cantypicallymakedecisionsabouthoworwhethertodeliverapacketbasedonthe
sourceanddestinationaddressesofthepacket.Firewallsaretypicallyasubspeciesof
routerwithanobsessivepersonality.Theycanbevery,veryconcernedaboutthepayload
ofpackets,whereasrouterstypicallydisregardpayloadsandjustdeliverthepackets.)
Inplanningacity,youcanplanhowstreetsintersectwitheachother,andcanuseturnonly,
oneway,anddeadendstreetstoinfluencetrafficflows.YoumightwantMainStreettobe30
blockslong,witheachblockhavingupto99buildingseach.It'sprettyeasytoplanyourstreet
numberingsuchthateachblockinMainStreethasarangeofstreetnumbersincreasingby
100foreachblock.It'sveryeasytoknowwhatthe"startingnumber"ineachsubsequentblock
shouldbe.
InplanningIPsubnets,you'reconcernedwithbuildingtherightnumberofsubnets(streets)
withtherightnumberofavailablehostID's(buildingnumbers),andusingrouterstoconnect
thesubnetstoeachother(intersections).Rulesaboutallowedsourceanddestination
addressesspecifiedintherouterscanfurthercontroltheflowoftraffic.Firewallscanactlike
obsessivetrafficcops.
Forthepurposesofthisanswer,buildingoursubnetsisouronlymajorconcern.Insteadof
workingindecimal,asyouwouldwithurbanplanning,youworkinbinarytodescribethe
boundsofeachsubnet.
Continuedon:HowdoesIPv4SubnettingWork?
(Yes...wereachedthemaximumsizeofananswer(30000characters).)
editedJan5'15at2:59

answeredAug4'09at15:51

user6607

EvanAnderson

103

126k

12

144

286

62 wow!+00000001.Nowgodosomework!LeComteduMerdefouAug4'09at15:56
14 +0x1Ididn'thavetimetogointothebinary.:)MuraliSuriarAug4'09at15:57
37 Greatcontent,butwaylongerthanwhatIprefertoseeonthissite.ahardenAug4'09at16:17
9

@Joseph:It'salecturethatI'vedeliveredtoomanytimesformyowngood.>smile<I'lllookatyourbinary
section.I'mloathetoteachaboutmath(whichisreallywhatunderstandingbinaryiscountinginbase2)
becauseI'mnotverygoodatit.EvanAndersonAug4'09at16:18

25 Don'tbreakitup.JosephKernAug4'09at17:22

Continuedfrom:HowdoesIPv4SubnettingWork?
YourISPgivesyoutherangethenetworkID192.168.40.0/24
(11000000.10101000.00101000.00000000).Youknowthatyou'dliketouseafirewall/router
devicetolimitcommunicationbetweendifferentpartsofyournetwork(servers,client
computers,networkequipment)and,assuch,you'dliketobreakthesevariouspartsofyour
networkupintoIPsubnets(whichthefirewall/routerdevicecanthenroutebetween).
Youhave:
12servercomputers,butyoumightgetupto50%more
9switches
97clientcomputers,butyoumightgetmore
What'sagoodwaytobreakup192.168.40.0/24intothesepieces?
Thinkinginevenpowersoftwo,andworkingwiththelargernumbersofpossibledevices,you
cancomeupwith:
18servercomputersNextlargestpoweroftwois32
9switchesNextlargestpoweroftwois16
97clientcomputersNextlargestpoweroftwois128
InagivenIPsubnet,therearetwoaddressesreservedthatcan'tbeusedasvaliddeviceIP
addressestheaddresswithallzerosinthehostIDportionandtheaddresswithallonesin

http://serverfault.com/questions/49765/how-does-ipv4-subnetting-work/49836#49836

7/14

30/08/2016

networking - How does IPv4 Subnetting Work? - Server Fault

thehostIDportion.Assuch,foranygivenIPsubnet,thenumberofhostaddressesavailable
istwotothepowerofthequantityof32minusthenumberofbitsinthesubnetmask,minus2.
So,inthecaseof192.168.40.0/24wecanseethatthesubnetmaskhas24bits.Thatleaves8
bitsavailableforhostIDs.Weknowthat2tothe8thpoweris256meaningthat256possible
combinationsofbitsfitintoaslot8bitswide.Sincethe"11111111"and"00000000"
combinationsofthose8bitsaren'tallowableforhostIDs,thatleavesuswith254possible
hoststhatcanbeassignedinthe192.168.40.0/24network.
Ofthose254hosts,itlookslikewecanfittheclientcomputers,switches,andserver
computersintothatspace,right?Let'stry.
Youhave8bitsofsubnetmaskto"playwith"(theremaining8bitsoftheIPaddress
192.168.40.0/24notcoveredbythesubnetmaskprovidedbyyourISP).Wehavetoworkout
awaytousethose8bitstocreateanumberofuniquenetworkIDsthatcanaccommodatethe
devicesabove.
Startwiththelargestnetworktheclientcomputers.Youknowthatthenextlargerpowerof
twofromthenumberofpossibledevicesis128.Thenumber128,inbinary,is"10000000".
Fortunatelyforus,thatfitsintothe8bitslotwehavefree(ifitdidn't,thatwouldbean
indicationthatourstartingsubnetistoosmalltoaccommodateallourdevices).
Let'stakeournetworkID,asprovidedbyourISP,andaddasinglebitofsubnetmasktoit,
breakingitupintotwonetworks:
11000000.10101000.00101000.00000000192.168.40.0networkID
11111111.11111111.11111111.00000000Oldsubnetmask(/24)
11000000.10101000.00101000.00000000192.168.40.0networkID
11111111.11111111.11111111.10000000Newsubnetmask(/25)
11000000.10101000.00101000.10000000192.168.40.128networkID
11111111.11111111.11111111.10000000Newsubnetmask(/25)

Lookoverthatuntilitmakessense.Weincreasedthesubnetmaskbyonebitinlength,
causingthenetworkIDtocoveronebitthatwouldhavebeenusedforhostID.Sincethatone
bitcanbeeitherzeroorone,we'veeffectivelysplitour192.168.40.0networkintotwo
networks.ThefirstvalidIPaddressinthe192.168.40.0/25networkwillbethefirsthostIDwith
a"1"intherightmostbit:
11000000.10101000.00101000.00000001192.168.40.1Firstvalidhostinthe
192.168.40.0/25network

Thefirstvalidhostinthe192.168.40.128networkwill,likewise,bethefirsthostIDwitha"1'in
therightmostbit:
11000000.10101000.00101000.10000001192.168.40.129Firstvalidhostinthe
192.168.40.128/25network

ThelastvalidhostineachnetworkwillbethehostIDwitheverybitexcepttherightmostbit
setto"1":
11000000.10101000.00101000.01111110192.168.40.126Lastvalidhostinthe
192.168.40.0/25network
11000000.10101000.00101000.11111110192.168.40.254Lastvalidhostinthe
192.168.40.128/25network

So,inthisway,we'vecreatedanetworklargeenoughtoholdourclientcomputers,anda
secondnetworkthatwecanthenapplythesameprincipletobreakdownintoyetsmaller
networks.Let'smakeanote:
Clientcomputers192.168.40.0/25ValidIPs:192.168.40.1192.168.40.126
Now,tobreakdownthesecondnetworkforourserversandswitches,wedothesamething.
Wehave12servercomputers,butwemightbuyupto6more.Let'splanon18,whichleaves
usthenexthighestpowerof2as32.Inbinary,32is"100000",whichis6bitslong.Wehave7
bitsofsubnetmaskleftin192.168.40.128/25,sowehaveenoughbitstocontinue"playing".
Addingonemorebitofsubnetmaskgivesustwomorenetworks:
11000000.10101000.00101000.10000000192.168.40.128networkID
11111111.11111111.11111111.10000000Oldsubnetmask(/25)
11000000.10101000.00101000.10000000192.168.40.128networkID
11111111.11111111.11111111.11000000Newsubnetmask(/26)
11000000.10101000.00101000.10000001192.168.40.129Firstvalidhostinthe
192.168.40.128/26network
11000000.10101000.00101000.10111110192.168.40.190Lastvalidhostinthe
192.168.40.128/26network
11000000.10101000.00101000.11000000192.168.40.192networkID
11111111.11111111.11111111.11000000Newsubnetmask(/26)
11000000.10101000.00101000.11000001192.168.40.193Firstvalidhostinthe
192.168.40.192/26network
11000000.10101000.00101000.11111110192.168.40.254Lastvalidhostinthe
192.168.40.192/26network

So,nowwe'vebrokenup192.168.40.128/25intotwomorenetworks,eachofwhichhas26
bitsofsubnetmask,oratotalof62possiblehostIDs2^(3226)2.
Thatmeansthatbothofthosenetworkshaveenoughaddressesforourserversandswitches!
Let'smakenotes:

http://serverfault.com/questions/49765/how-does-ipv4-subnetting-work/49836#49836

8/14

30/08/2016

networking - How does IPv4 Subnetting Work? - Server Fault

Servers192.168.40.128/26ValidIPs:192.168.40.129192.168.40.190
Switches192.168.40.192/26ValidIPs:192.168.40.193192.168.40.254
Thistechniqueiscalledvariablelengthsubnetmasking(VLSM)and,ifproperlyapplied,
causes"corerouters"tohavesmallerroutingtables(throughaprocesscalled"route
summarization").InthecaseofourISPinthisexample,theycanbetotallyunawareofhow
we'vesubnetted192.168.40.0/24.Iftheirrouterhasapacketboundfor192.168.40.206(oneof
ourswitches),theyneedonlyknowtopassittoourrouter(since192.168.40.206matchesthe
networkidandsubnetmask192.168.40.0/24intheirrouter'sroutingtable)andourrouterwill
getittothedestination.Thiskeepsoursubnetroutesoutoftheirroutingtables.(I'msimplifying
here,butyougettheidea.)
Youcanplanverygeographicallylargenetworksinthissameway.Aslongasyoudotheright
"urbanplanning"upfront(anticipatingthenumberofhostsineachsubnetworkwithsome
accuracyandaneyetothefuture)youcancreatealargeroutinghierarchythat,atthecore
routers,"summarizes"toaverysmallnumberofroutes.Aswesawabove,themoreroutes
thatareinarouter'sroutingtablethesloweritperformsitsjob.DesigninganIPnetworkwith
VLSMandkeepingroutingtablessmallisaGoodThing(tm).

TheUnrealismofExamples
Thefictionalworldinthisansweris,obviously,fictional.Typicallyyoucanmakesubnetson
modernswitchedEthernetwithmorehoststhan254(trafficprofiledependent).Ashasbeen
pointedoutincomments,using/24networksbetweenroutersisn'tconsistentwithReal
Life(tm).Itmakesforcuteexamples,butisawasteofaddressspace.Typically,a/30ora/31
(seehttp://www.faqs.org/rfcs/rfc3021.htmlfordetailsonhow/31'sworktheyarebeyondthe
scopeofthisanswerforsure)networkisusedonlinksthatarestrictlypointtopointbetween
tworouters.
editedAug16'14at5:00

communitywiki
4revs,4users96%
JosephKern

Here'sthesecondpart.:)JosephKernJan25'11at0:55
Smallerror:Thecoderightafter"Thelastvalidhost..."revertsbacktocallingit"thefirstvalidhost."Iassume

thatshouldstillsay"last."JoeCool1986Jul8'13at13:40
@JoeCool1986Goodcatch.EvanAndersonJul8'13at13:47
I'mgoingtoupvotethisanswertomakesurethattwoanswersarekeptinorder.l46kokAug22'13at

16:24
Onthepartwhereyoucreatetwosubnetsfrom192.168.40.128andcreateannetworkIDof192.168.40.192,

wheredidthe192comefrom?user6607Jan5'15at1:59

Subnetting
Subnettingisnotdifficultbutitcanbeintimidating.Solet'sstartwiththesimplestpossible
step.Learningtocountinbinary.
Binary
Binaryisabase2countingsystem.Consistingofonlytwonumbers(1and0).Counting
proceedsinthismanner.
1=001(0+0+1=1)
2=010(0+2+0=2)
3=011(0+2+1=3)
4=100(4+0+0=4)
5=101(4+0+1=5)

Soifyoujustimaginethateach1isaplaceholderforavalue(allbinaryvaluesarepowersof
two)
11111=31
16+8+4+2+1=31

So...100000=32.And10000000=128.AND11111111=255.
WhenIsay,"Ihaveasubnetmaskof255.255.255.0",Ireallymean,"Ihaveasubnetmaskof
11111111.11111111.11111111.00000000."Weusesubnetsasashorthand.
Theperiodsintheaddress,separateevery8binarydigits(anoctet).ThisiswhyIPv4isknown
asa32bit(8*4)addressspace.
WhySubnet?
IPv4addresses(192.168.1.1)areinshortsupply.Subnettinggivesusawaytoincreasethe
amountofavailablenetworks(orhosts).Thisisforadministrativereasonsandtechnical
reasons.
EachIPaddressisbrokenintotwoseparateportions,thenetworkandthehost.Bydefaulta
ClassCaddress(192.168.1.1)usesthefirst3octets(192.168.1)forthenetworkportionofthe

http://serverfault.com/questions/49765/how-does-ipv4-subnetting-work/49836#49836

9/14

30/08/2016

networking - How does IPv4 Subnetting Work? - Server Fault

address.andthe4thoctet(.1)asthehostportion.
BydefaultanipaddressandsubnetmaskforaClassCadresslookslikethis
IP192.168.1.1
Subnet255.255.255.0

Inbinarylikethis
IP11000000.10101000.00000001.00000001
Subnet11111111.11111111.11111111.00000000

Lookatthebinaryexampleagain.NoticehowIsaidthefirstthreeoctetsareusedforthe
network?Noticehowthenetworkportionisallones?That'sallsubnettingis.Let'sexpand.
GiventhatIhaveasingleoctetformyhostportion(intheaboveexample).IcanONLYever
have256hosts(256isthemaxvalueofanoctet,countingfrom0).Butthere'sanothersmall
trick:youneedtosubtract2hostaddressesfromtheavailableones(currently256).Thefirst
addressintherangewillbeforthenetwork(192.168.1.0)andthelastaddressintherangewill
bethebroadcast(192.168.1.255).Soyoureallyhave254availableaddressesforhostsinone
network.
ACaseStudy
Let'ssayIgaveyouthethefollowingpieceofpaper.
Create4networkswith192.168.1.0/24.

Let'stakealookatthis.The/24iscalledCIDRnotation.Ratherthanreferencingthe
255.255.255.0wejustreferencethebitsweneedforthenetwork.Inthiscaseweneed24bits
(3*8)froma32bitaddress.Writingthisoutinbinary
11111111.11111111.11111111.00000000=255.255.255.0
8bits+8bits+8bits+0bits=24bits

Nextweknowweneedfigureouthowmanysubnetsweneed.Lookslike4.Sinceweneedto
createmorenetworks(currentlyweonlyhaveone)letsflipsomebits
11111111.11111111.11111111.00000000=255.255.255.0=1NetworkOR/24
11111111.11111111.11111111.10000000=255.255.255.128=2NetworksOR/25
11111111.11111111.11111111.11000000=255.255.255.192=4Networks(rememberpowers
of2!)OR/26

Nowthatwe'vedecidedona/26let'sstartallocatinghosts.Alittlesimplemath:
32(bits)26(bits)=6(bits)forhostaddresses.

Wehave6bitstoallocateineachnetworkforhosts.Rememberingthatweneedtosubtract2
foreachnetwork.
h=hostbits
2^h2=hostsavailable
2^62=62hosts
Finallywehave62hostsin4networks,192.168.1.0/26

Nowweneedtofigureoutwherethehostsgo.Backtothebinary!
11111111.11111111.11111111.00,000000[thecommaisthenewnetwork/hostsdivision]
Begintocalculate:
11000000.10101000.00000001.00,000000=192.168.1.0[FirstIP=NetworkAdress]
11000000.10101000.00000001.00,000001=192.168.1.1[FirstHostIP]
11000000.10101000.00000001.00,000010=192.168.1.2[SecondHostIP]
11000000.10101000.00000001.00,000011=192.168.1.3[ThirdHostIP]
Andsoon...until...
11000000.10101000.00000001.00,111110=192.168.1.62[SixtySecondHostIP]
11000000.10101000.00000001.00,111111=192.168.1.63[LastIP=BroadcastAddress]
So...OntotheNEXTnetwork....
11000000.10101000.00000001.01,000000=192.168.1.64[FirstIP=NetworkAddress]
11000000.10101000.00000001.01,000001=192.168.1.65[FirstHostIP]
11000000.10101000.00000001.01,000010=192.168.1.66[SecondHostIP]
Andsoon...until...
11000000.10101000.00000001.01,111110=192.168.1.126[SixtySecondHostIP]
11000000.10101000.00000001.01,111111=192.168.1.127[LastIP=BroadcastAddress]
So...OntotheNEXTnetwork....
11000000.10101000.00000001.10,000000=192.168.1.128[FirstIP=NetworkAddress]
11000000.10101000.00000001.10,000001=192.168.1.129[FirstHostIP]
Etc...

Inthiswayyoucancalculatetheentiresubnet.
WildCardsAwildcardmaskisaninvertedsubnetmask.

http://serverfault.com/questions/49765/how-does-ipv4-subnetting-work/49836#49836

10/14

30/08/2016

networking - How does IPv4 Subnetting Work? - Server Fault

11111111.11111111.11111111.11000000=255.255.255.192[Subnet]
00000000.00000000.00000000.00111111=0.0.0.63[WildCard]

Further
Googlefortheterms'supernetting',and'VLSM(variablelengthsubnetmask)',formore
advancedtopics.
IcanseenowthatItooktoolonginresponding...sigh
editedNov30'11at15:53

answeredAug4'09at15:58

JosephKern
7,505

23

52

1 +1Veryuseful.boehjJul16'11at0:57
1 "GiventhatIhaveasingleoctetformyhostportion(intheaboveexample).IcanONLYeverhave255
hosts(255isthemaxvalueofanoctet).Butthere'sanothersmalltrick:youneedtosubtract2host
addressesfromtheavailableones(currently255).Thefirstaddressintherangewillbeforthenetwork
(192.168.1.0)andthelastaddressintherangewillbethebroadcast(192.168.1.255).Soyoureallyhave
253availableaddressesforhostsinonenetwork."...Thisisincorrect.joeqwertyNov29'11at19:08
1 Thereare256possiblevaluesfortheoctet:0through255,foratotalof256.2562(networkandbroadcast
addresses)=254possiblehostaddresses.joeqwertyNov29'11at19:37
Oops.Thanks!:)Offbyone,IhavenoideahowImanagedthatparticularfeat.JosephKernNov30'11

at15:52
1 1Sorry,buttherehaven'tbeen"Classes"sinceRFC1519in1993,nobodyshouldbetalkingaboutthem
outsideofahistoricalcontext.They'reconfusingandcausealotofmisconceptions.ChrisSAug8'13at
15:02

Abriefhistorylesson:originally,unicastIPv4addressesweredividedinto3classes,eachwith
anassociated'default'masklength(calledtheclassfulsubnetmask)
ClassA:Anythingintherange1.0.0.0>127.255.255.255.Classfulsubnetmaskof
255.0.0.0(/8inCIDRnotation)
ClassB:Anythingintherange128.0.0.0>191.255.255.255.Classfulsubnetmaskof
255.255.0.0(/16inCIDRnotation)
ClassC:Anythingintherange192.0.0.0>223.255.255.255.Classfulsubnetmaskof
255.255.255.0(/24inCIDRnotation)
TheideawasthatdifferentsizedorganisationscouldbeallocatedadifferentclassofIP
address,tomakeefficientuseofIPaddressspace.
However,asIPnetworksgrew,itbecameclearthatthisapproachhaditsproblems.Toname
butthree:
Inaclassfulworld,allsubnetshadtohaveamaskof/8,/16,or/24.Thismeantthatthe
smallestsubnetthatcouldbeconfiguredwasa/24,whichallowedfor254hostaddresses(.0
and.255beingreservedasthethenetworkandbroadcastaddresses,respectively).Thiswas
tremendouslywasteful,particularlyonpointtopointlinkswithonlytworoutersattachedto
them.
Evenafterthisrestrictionwasrelaxed,earlierroutingprotocols(e.g.RIPv1)didnotadvertise
themasklengthassociatedwithanIPprefix.Intheabsenceofaspecificmask,itwoulduse
eitherthemaskofadirectlyconnectedinterfaceinthesameclassfulnetwork,orfallbackto
usingtheclassfulmask.Forexample,ifyouwantedtousethenetwork172.16.0.0forinter
routerlinkswith/30masks,allsubnetsfrom172.16.0.0172.16.255.255wouldhavetohave
a/30mask(16384subnets,eachwith2useableIPs).
Theroutingtablesofinternetroutersbegantotakeupmoreandmorememorythiswas/is
knownasthe'routingtableexplosion'.Ifaproviderhad16contiguous/24networks,for
example,theywouldneedtoadvertiseall16prefixes,ratherthanasinglesummarythat
coveredtheentirerange.
Tworelatedrefinementsallowedustomovebeyondtheabovelimitations.
1.VariableLengthSubnetMasks(VLSM)
2.CIDR(Classlessinterdomainrouting)
VLSMreferstotheabilityofaroutingprotocoltosupportdifferentsubnetmaskswithinthe
sameclassfulnetwork.Forexample:
192.168.1.0/24

Couldbesplitinto:
192.168.1.0/25
192.168.1.128/26
192.168.1.192/27
192.168.1.224/27

Whichallowedformuchmoreefficientuseofaddressspacesubnetscouldbesizedcorrectly
forthenumberofhosts/routersthatwouldbeattachedtothem.

http://serverfault.com/questions/49765/how-does-ipv4-subnetting-work/49836#49836

11/14

30/08/2016

networking - How does IPv4 Subnetting Work? - Server Fault

CIDRtakesVLSMandextendsittheotherwayinadditiontosplittingasingleclassfulnetwork
intosmallersubnets,CIDRallowsfortheaggregationofmultipleclassfulnetworksintoasingle
summary.Forexample,thefollowingClassB(/16)networks:
172.16.0.0/16
172.17.0.0/16
172.18.0.0/16
172.19.0.0/16

Canbeaggregate/summarisedwithasingleprefix:
172.16.0.0/14

Intermsofsubnetting:asubnetmaskis32bitslong.Themasklengthdenoteshowmanybits
identifythenetworkportionoftheaddress.Forexample:
10.1.1.0/24

Theclassfulsubnetmaskis/8
Theactualsubnetmaskis/24
16bits(248)havebeen'borrowed'fortheuseofsubnetting.
Thismeansthat,assumingtheentire10.0.0.0/8networkissubnettedinto/24s,thattherewill
be65536(2^16)subnetswithinthisrange.(Thisisassumingthattheplatformyouareusing
supportssubnetnumbersof0and255.SeeCisco'sipsubnetzero).
Thereare8bitsremaininginthe'hostportion'oftheaddress.Thismeansthereare256
availableIPaddresses(2^8),ofwhich2arereserved(10.1.1.0isthenetworkaddress,
10.1.1.255isthesubnetdirectedbroadcastaddress).Thisleaves254usableIPaddresseson
thissubnet.((2^8)2)
answeredAug4'09at15:53

MuraliSuriar
7,363

30

57

4 Therewereactually5classes.dbasnettMay19'10at12:40
5 True,butdowereallyneedtogetintomulticastandreservedclassEaddressingforan'introtosubnetting'
question?:)MuraliSuriarMay19'10at20:00
2 Youbroughthistoryintoanintroquestion...Thenleftitincomplete.Notsurewhichisworse.ChrisSAug8
'13at14:51

Networkranges:networksarealwaysreferencedby2numbers:onetodeterminethenetwork,
andanothertodeterminewhichcomputer(orhost)isonthatnetwork.Aseachnertwork
addressis32bitslong,bothnumbershavetofitinthese32bits.
Networknumberingisimportant,asitsthisthatICANNhandsoutwhenyouaskforanetwork
IPrange.Ifwedidn'thaveit,noonewouldbeabletotellthedifferencebetweenmynetwork
andAT&Ts.Sowhilethesenumbersmustbeunique,nooneelsewantstoassignnumbersto
thehoststhatareonmynetwork.Hencethesplitthefirstpartismanagedbythenetwork
people,thesecondpartisallminetogivetowhatevermachinesIwant.
Thenetworknumberisn'tfixedatacertainnumberofbitsforexample,ifIhadonly200
machinestomanagemyself,I'dbeperfectlyhappywithanetworknumberthatused24bits,
leavingmewithonly8bitsformyselfwhichisenoughforupto255hosts.Asthenetwork
numberuses24bits,wecanhavelotsofthem,meaninglotsofpeoplecanhavetheirown
networks.
InthepastthiswasreferredtoasaclassCnetwork.(classBused16bitsfornetworknumber,
andclassAused8bits,sothereareonlyafewclassAnetworksinexistence).
Nowadays,thisnamingconventionhasfallenoutoffashion.Itwasreplacedwiththeconcept
calledCIDR.CIDRexplicitlyputsthenumberofbitsforyourhostsaftertheslash.Somy
exampleabove(theclassC)isnowreferredtoasaCIDR/24.
Thisdoesgiveusalittlemoreflexibility,beforeifIhad300hoststomanage,I'dneedaclassB
network!Now,Icanjustgeta/23CIDR,soIhave9bitsforme,and23bitsforthenetwork
number.ICANNmaynothavethesekindofnetworksout,butifIhaveaninternalone,oram
rentingapartialnetworkfromanISP,thismakesiteasiertomanageespeciallyasalltheir
customerscanbegivena/29(leavingme..3bitsoramaximumof8machines)whichallows
morepeopletohavetheirownlittlesliceoftheavailableIPaddresses.UntilwegetIPv6,this
isquiteimportant.

However...whileIknowa/24CIDRistheequivalentoftheoldClassCnetwork,anda/16is
classBanda/8isaclassA...Iamstillstumpedtryingtocalculatea/22inmyhead.
Fortunatelytherearetoolsthatdothisforme:)
Howeverifyouknowa/24is8bitsforhosts(and24bitsfornetwork),thenIknowa/23gives
meanextrabitwhichdoublesthenumberofhosts.
answeredAug4'09at15:12

http://serverfault.com/questions/49765/how-does-ipv4-subnetting-work/49836#49836

12/14

30/08/2016

networking - How does IPv4 Subnetting Work? - Server Fault


gbjbaanb
3,450

15

25

1Sorry,butmentioningclassesoutsidea"historical"referenceisinappropriatethesedays.Theydidn't"fall

outoffashion"theywereofficiallydeprecatedbyRFC1519in1993.Theyareconfusingasallh*llandcause
abunchofmisconceptions.ChrisSAug8'13at14:56

Whiletheaboveiscorrect(sorry,TLDR),calculatingsubnetsstillcausesmanynetwork
administratorsalotofgrief.Thereactuallyisaveryeasywaytodosubnetcalculation,youcan
domostofitinyourhead,andthereisverylittleyouhavetomemorize.Formostapplications,
it'snotevennecessarytounderstandthebinaryrepresentation,thoughitishelpfulfora
completeunderstandingofsubnetting.HereIwillonlydiscussIPv4IPv6isoutsideofthe
scopeofthisdiscussion.

Rememberthis:
Therearethreekeythingstoremember:allsubnetsarebasedonpowersoftwo,andthere
aretwokeynumbers:256and32.Moreonthatlater.
First,letslookatatablecontainingpowersof2:
2^0=1
2^1=2
2^2=4
2^3=8
2^4=16
2^5=32
2^6=64
2^7=128
2^8=256

Calculatingpowersof2iseasy:eachintegerincreaseinthepowerdoublestheresult.1+1=2,
2+2=4,4+4=8,8+8=16,andsoon.Thetotalnumberofaddressesinasubnetmustalwaysbe
apowerof2.
SinceeachoctetofanIPv4subnetgoesupto256,256isaveryimportantnumberandforms
thebasisfortherestofthemath.

Sizingthesubnet
We'llstartwithaneasyquestion:"howmanyaddressesinasubnetifthemaskis
255.255.255.248?"Wewillignorethefirstthreeoctetsfornowandlookatthelast.Hereis
howeasyitis:subtract248from256.256minus248equals8.Thereare8addresses
available(includingthenetworkandbroadcastaddresses).Thereversealsoworks:"ifIwant
tohaveasubnetwith16addresses,whatwillthesubnetmaskbe?"256minus16equals240.
Thesubnetmaskwillbe255.255.255.248.
Nowifwewanttoexpandbeyond256addresses(historically,a"classC"),itgetsonlyatiny
bitmorecomplicated:ifourlastoctetis0andourthirdoctetis,say,240,(255.255.240.0)then
wedothemathonthethirdoctetandfindthattherewouldbe16addresses.Sowemultiply16
by256(thenumberofaddressesinthelastoctet)toget4,096.Ifboththelasttwooctetsare
0,(ex.255.240.0.0)thenwetakethesubtractionresultfromthesecondoctet(we'llsayit's16
again),multiplybut256(addressesinthethirdoctet),multiplyagainby256(addressesinthe
lastoctet)toget1,048,576addresses.Easyasthat!(OK,sothereverseisalittlemore
difficult.Ifwewantasubnetwith1,048,576addresses,we'llhavetodividethatnumberby256
acoupleoftimestogetanumberwecansubtractfrom256.)

Networkaddress
Nowthatweknowhowtocalculatethesubnetmask,howdowefigureoutwhatthenetwork
addressis?That'seasy:it'salwaysamultipleofthenumberofaddressesinoursubnet.Soif
wehave16addressesinoursubnet,thepossiblenetworkaddresseswillbe0,16,32,48,64,
andsoonupto240.(Notethat0isavalidmultipleofanynumber,asanynumbermultiplied
by0equals0.)
And,ofcourse,thebroadcastaddresswillbethelastaddressinthescope.Soifwehave16
addressinoursubnet,andwe'vechosenanetworkaddressof10.3.54.64,thebroadcast
addresswillbe(64+161=79)10.3.54.79.

CIDRNotation
SohowaboutCIDRnotation?HowdotranslatethattoandfromanIPv4stylesubnetmask?
Rememberourpowersoftwo?Well,nowwehaveanotherkeynumbertorememberbesides
256:32.Remember,CIDRnotationdescribesthenumberofsignificantbitsintheIPv4
address,andthereare32bitsinanIPv4address,8foreachoctet.Soifwehaveasubnet
maskof255.255.255.240,thatis16addresses.Ifwelookatour"powersof2"tableabove,we
seethat16istwotothefourthpower(2^4).Sowesubtractthatpowernumber4from32
andget28.OurCIDRnotationforasubnetmaskof255.255.255.240,ourCIDRnotationis
/28.
AndifwearegivenaCIDRof/28,wesubtractthat(28)from32toget4raise2tothat(4th)
power(2^4)toget16thensubtractthat(16)from256toget240or255.255.255.240.

http://serverfault.com/questions/49765/how-does-ipv4-subnetting-work/49836#49836

13/14

30/08/2016

networking - How does IPv4 Subnetting Work? - Server Fault


answeredMar14'15at5:51

communitywiki
JonathanJ

thankyou.ButIamstillfuzzyonhowthepcusesthesubnetmask.Whenanapplicationonapcwantsto

senddata,itencapsulatesitintoapacket.Doesthesubnetmaskdeterminehowapacketisencapsulated?
Forexampleifthepcwantedtosendapacketonthelocalnet,itwoulduseanethernetframe
en.wikipedia.org/wiki/Ethernet_frameandifitwantedoutsidethenetworkwouldituseatcppacket
en.wikipedia.org/wiki/?aquagremlinMay21'15at12:30
Basically,IdonotknowHOWapcdetermineswheretosenditsdatato.Theethernetnetworkislikeabusit

goeseverywhere.Puttingapacketoutthroughtheethernetjackofapcisagenericeventthereforethe
packetitselfhastodeterminewhorespondstoit.Apacketthatisdestinedtopickedupbyalocaldevice
(switchorotherpconthelan)hastolookdifferentthanapacketthatisgoingtobepickedupbyarouter.
aquagremlinMay21'15at12:31

protectedbyvoretaq7 Aug15'12at19:49
Thankyouforyourinterestinthisquestion.Becauseithasattractedlowqualityorspamanswersthathadtoberemoved,postingananswernowrequires10reputation
onthissite(theassociationbonusdoesnotcount).
Wouldyouliketoansweroneoftheseunansweredquestionsinstead?

http://serverfault.com/questions/49765/how-does-ipv4-subnetting-work/49836#49836

14/14